<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="python,">










<meta name="description" content="Comprehensive Python Cheatsheet 来自github Contents  1. Collections: List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator. 2. Types: Type, String, Regular_Exp, Format, Numbers, Combinator">
<meta name="keywords" content="python">
<meta property="og:type" content="article">
<meta property="og:title" content="python备忘清单">
<meta property="og:url" content="https://srat1999.top/2020/01/03/python备忘清单/index.html">
<meta property="og:site_name" content="Stay hungry stay foolish">
<meta property="og:description" content="Comprehensive Python Cheatsheet 来自github Contents  1. Collections: List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator. 2. Types: Type, String, Regular_Exp, Format, Numbers, Combinator">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-03T14:12:12.239Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="python备忘清单">
<meta name="twitter:description" content="Comprehensive Python Cheatsheet 来自github Contents  1. Collections: List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator. 2. Types: Type, String, Regular_Exp, Format, Numbers, Combinator">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://srat1999.top/2020/01/03/python备忘清单/">





  <title>python备忘清单 | Stay hungry stay foolish</title>
  








<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Stay hungry stay foolish</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">srat1999's blog</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://srat1999.top/2020/01/03/python备忘清单/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="srat1999">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/uploads/pikachu.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Stay hungry stay foolish">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python备忘清单</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-01-03T22:09:50+08:00">
                2020-01-03
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/编程技术/" itemprop="url" rel="index">
                    <span itemprop="name">编程技术</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  13.1k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  81
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Comprehensive-Python-Cheatsheet"><a href="#Comprehensive-Python-Cheatsheet" class="headerlink" title="Comprehensive Python Cheatsheet"></a>Comprehensive Python Cheatsheet</h1><h2 id="来自github"><a href="#来自github" class="headerlink" title="来自github"></a>来自<a href="https://github.com/gto76/python-cheatsheet" target="_blank" rel="noopener">github</a></h2><h2 id="Contents"><a href="#Contents" class="headerlink" title="Contents"></a>Contents</h2><p><strong>&nbsp;&nbsp;&nbsp;</strong> <strong>1. Collections:</strong> <strong>&nbsp;</strong> <strong><a href="#list"><code>List</code></a></strong><strong>,</strong> <strong><a href="#dictionary"><code>Dictionary</code></a></strong><strong>,</strong> <strong><a href="#set"><code>Set</code></a></strong><strong>,</strong> <strong><a href="#tuple"><code>Tuple</code></a></strong><strong>,</strong> <strong><a href="#range"><code>Range</code></a></strong><strong>,</strong> <strong><a href="#enumerate"><code>Enumerate</code></a></strong><strong>,</strong> <strong><a href="#iterator"><code>Iterator</code></a></strong><strong>,</strong> <strong><a href="#generator"><code>Generator</code></a></strong><strong>.</strong><br><strong>&nbsp;&nbsp;&nbsp;</strong> <strong>2. Types:</strong> <strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</strong>  <strong><a href="#type"><code>Type</code></a></strong><strong>,</strong> <strong><a href="#string"><code>String</code></a></strong><strong>,</strong> <strong><a href="#regex"><code>Regular_Exp</code></a></strong><strong>,</strong> <strong><a href="#format"><code>Format</code></a></strong><strong>,</strong> <strong><a href="#numbers"><code>Numbers</code></a></strong><strong>,</strong> <strong><a href="#combinatorics"><code>Combinatorics</code></a></strong><strong>,</strong> <strong><a href="#datetime"><code>Datetime</code></a></strong><strong>.</strong><br><strong>&nbsp;&nbsp;&nbsp;</strong> <strong>3. Syntax:</strong> <strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</strong>  <strong><a href="#arguments"><code>Args</code></a></strong><strong>,</strong> <strong><a href="#inline"><code>Inline</code></a></strong><strong>,</strong> <strong><a href="#closure"><code>Closure</code></a></strong><strong>,</strong> <strong><a href="#decorator"><code>Decorator</code></a></strong><strong>,</strong> <strong><a href="#class"><code>Class</code></a></strong><strong>,</strong> <strong><a href="#duck-types"><code>Duck_Types</code></a></strong><strong>,</strong> <strong><a href="#enum"><code>Enum</code></a></strong><strong>,</strong> <strong><a href="#exceptions"><code>Exceptions</code></a></strong><strong>.</strong><br><strong>&nbsp;&nbsp;&nbsp;</strong> <strong>4. System:</strong> <strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</strong>  <strong><a href="#print"><code>Print</code></a></strong><strong>,</strong> <strong><a href="#input"><code>Input</code></a></strong><strong>,</strong> <strong><a href="#command-line-arguments"><code>Command_Line_Arguments</code></a></strong><strong>,</strong> <strong><a href="#open"><code>Open</code></a></strong><strong>,</strong> <strong><a href="#path"><code>Path</code></a></strong><strong>,</strong> <strong><a href="#oscommands"><code>Command_Execution</code></a></strong><strong>.</strong><br><strong>&nbsp;&nbsp;&nbsp;</strong> <strong>5. Data:</strong> <strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</strong>  <strong><a href="#json"><code>JSON</code></a></strong><strong>,</strong> <strong><a href="#pickle"><code>Pickle</code></a></strong><strong>,</strong> <strong><a href="#csv"><code>CSV</code></a></strong><strong>,</strong> <strong><a href="#sqlite"><code>SQLite</code></a></strong><strong>,</strong> <strong><a href="#bytes"><code>Bytes</code></a></strong><strong>,</strong> <strong><a href="#struct"><code>Struct</code></a></strong><strong>,</strong> <strong><a href="#array"><code>Array</code></a></strong><strong>,</strong> <strong><a href="#memory-view"><code>MemoryView</code></a></strong><strong>,</strong> <strong><a href="#deque"><code>Deque</code></a></strong><strong>.</strong><br><strong>&nbsp;&nbsp;&nbsp;</strong> <strong>6. Advanced:</strong> <strong>&nbsp;&nbsp;&nbsp;</strong>  <strong><a href="#threading"><code>Threading</code></a></strong><strong>,</strong> <strong><a href="#operator"><code>Operator</code></a></strong><strong>,</strong> <strong><a href="#introspection"><code>Introspection</code></a></strong><strong>,</strong> <strong><a href="#metaprograming"><code>Metaprograming</code></a></strong><strong>,</strong> <strong><a href="#eval"><code>Eval</code></a></strong><strong>,</strong> <strong><a href="#coroutine"><code>Coroutine</code></a></strong><strong>.</strong><br><strong>&nbsp;&nbsp;&nbsp;</strong> <strong>7. Libraries:</strong> <strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</strong>  <strong><a href="#progress-bar"><code>Progress_Bar</code></a></strong><strong>,</strong> <strong><a href="#plot"><code>Plot</code></a></strong><strong>,</strong> <strong><a href="#table"><code>Table</code></a></strong><strong>,</strong> <strong><a href="#curses"><code>Curses</code></a></strong><strong>,</strong> <strong><a href="#logging"><code>Logging</code></a></strong><strong>,</strong> <strong><a href="#scraping"><code>Scraping</code></a></strong><strong>,</strong> <strong><a href="#web"><code>Web</code></a></strong><strong>,</strong> <strong><a href="#profiling"><code>Profile</code></a></strong><strong>,</strong><br><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</strong> <strong><a href="#numpy"><code>NumPy</code></a></strong><strong>,</strong> <strong><a href="#image"><code>Image</code></a></strong><strong>,</strong> <strong><a href="#animation"><code>Animation</code></a></strong><strong>,</strong> <strong><a href="#audio"><code>Audio</code></a></strong><strong>.</strong></p>
<h2 id="Main"><a href="#Main" class="headerlink" title="Main"></a>Main</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:     <span class="comment"># Runs main() if file wasn't imported.</span></span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>
<h2 id="List"><a href="#List" class="headerlink" title="List"></a>List</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;list&gt; = &lt;list&gt;[from_inclusive : to_exclusive : ±step_size]</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;list&gt;.append(&lt;el&gt;)            <span class="comment"># Or: &lt;list&gt; += [&lt;el&gt;]</span></span><br><span class="line">&lt;list&gt;.extend(&lt;collection&gt;)    <span class="comment"># Or: &lt;list&gt; += &lt;collection&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;list&gt;.sort()</span><br><span class="line">&lt;list&gt;.reverse()</span><br><span class="line">&lt;list&gt; = sorted(&lt;collection&gt;)</span><br><span class="line">&lt;iter&gt; = reversed(&lt;list&gt;)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">sum_of_elements  = sum(&lt;collection&gt;)</span><br><span class="line">elementwise_sum  = [sum(pair) <span class="keyword">for</span> pair <span class="keyword">in</span> zip(list_a, list_b)]</span><br><span class="line">sorted_by_second = sorted(&lt;collection&gt;, key=<span class="keyword">lambda</span> el: el[<span class="number">1</span>])</span><br><span class="line">sorted_by_both   = sorted(&lt;collection&gt;, key=<span class="keyword">lambda</span> el: (el[<span class="number">1</span>], el[<span class="number">0</span>]))</span><br><span class="line">flatter_list     = list(itertools.chain.from_iterable(&lt;list&gt;))</span><br><span class="line">product_of_elems = functools.reduce(<span class="keyword">lambda</span> out, x: out * x, &lt;collection&gt;)</span><br><span class="line">list_of_chars    = list(&lt;str&gt;)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;int&gt; = &lt;list&gt;.count(&lt;el&gt;)     <span class="comment"># Returns number of occurrences. Also works on strings.</span></span><br><span class="line">index = &lt;list&gt;.index(&lt;el&gt;)     <span class="comment"># Returns index of first occurrence or raises ValueError.</span></span><br><span class="line">&lt;list&gt;.insert(index, &lt;el&gt;)     <span class="comment"># Inserts item at index and moves the rest to the right.</span></span><br><span class="line">&lt;el&gt; = &lt;list&gt;.pop([index])     <span class="comment"># Removes and returns item at index or from the end.</span></span><br><span class="line">&lt;list&gt;.remove(&lt;el&gt;)            <span class="comment"># Removes first occurrence of item or raises ValueError.</span></span><br><span class="line">&lt;list&gt;.clear()                 <span class="comment"># Removes all items. Also works on dictionary and set.</span></span><br></pre></td></tr></table></figure>
<h2 id="Dictionary"><a href="#Dictionary" class="headerlink" title="Dictionary"></a>Dictionary</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;view&gt; = &lt;dict&gt;.keys()                          <span class="comment"># Coll. of keys that reflects changes.</span></span><br><span class="line">&lt;view&gt; = &lt;dict&gt;.values()                        <span class="comment"># Coll. of values that reflects changes.</span></span><br><span class="line">&lt;view&gt; = &lt;dict&gt;.items()                         <span class="comment"># Coll. of key-value tuples that reflects chgs.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">value  = &lt;dict&gt;.get(key, default=<span class="literal">None</span>)          <span class="comment"># Returns default if key is missing.</span></span><br><span class="line">value  = &lt;dict&gt;.setdefault(key, default=<span class="literal">None</span>)   <span class="comment"># Returns and writes default if key is missing.</span></span><br><span class="line">&lt;dict&gt; = collections.defaultdict(&lt;type&gt;)        <span class="comment"># Creates a dict with default value of type.</span></span><br><span class="line">&lt;dict&gt; = collections.defaultdict(<span class="keyword">lambda</span>: <span class="number">1</span>)     <span class="comment"># Creates a dict with default value 1.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;dict&gt; = dict(&lt;collection&gt;)                     <span class="comment"># Creates a dict from coll. of key-value pairs.</span></span><br><span class="line">&lt;dict&gt; = dict(zip(keys, values))                <span class="comment"># Creates a dict from two collections.</span></span><br><span class="line">&lt;dict&gt; = dict.fromkeys(keys [, value])          <span class="comment"># Creates a dict from collection of keys.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;dict&gt;.update(&lt;dict&gt;)                           <span class="comment"># Adds items. Replaces ones with matching keys.</span></span><br><span class="line">value = &lt;dict&gt;.pop(key)                         <span class="comment"># Removes item or raises KeyError.</span></span><br><span class="line">&#123;k <span class="keyword">for</span> k, v <span class="keyword">in</span> &lt;dict&gt;.items() <span class="keyword">if</span> v == value&#125;    <span class="comment"># Returns set of keys that point to the value.</span></span><br><span class="line">&#123;k: v <span class="keyword">for</span> k, v <span class="keyword">in</span> &lt;dict&gt;.items() <span class="keyword">if</span> k <span class="keyword">in</span> keys&#125;  <span class="comment"># Returns dictionary filtered by keys.</span></span><br></pre></td></tr></table></figure>
<h3 id="Counter"><a href="#Counter" class="headerlink" title="Counter"></a>Counter</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> collections <span class="keyword">import</span> Counter</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>colors = [<span class="string">'blue'</span>, <span class="string">'red'</span>, <span class="string">'blue'</span>, <span class="string">'red'</span>, <span class="string">'blue'</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>counter = Counter(colors)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>counter[<span class="string">'yellow'</span>] += <span class="number">1</span></span><br><span class="line">Counter(&#123;<span class="string">'blue'</span>: <span class="number">3</span>, <span class="string">'red'</span>: <span class="number">2</span>, <span class="string">'yellow'</span>: <span class="number">1</span>&#125;)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>counter.most_common()[<span class="number">0</span>]</span><br><span class="line">(<span class="string">'blue'</span>, <span class="number">3</span>)</span><br></pre></td></tr></table></figure>
<h2 id="Set"><a href="#Set" class="headerlink" title="Set"></a>Set</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;set&gt; = set()</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;set&gt;.add(&lt;el&gt;)                                 <span class="comment"># Or: &lt;set&gt; |= &#123;&lt;el&gt;&#125;</span></span><br><span class="line">&lt;set&gt;.update(&lt;collection&gt;)                      <span class="comment"># Or: &lt;set&gt; |= &lt;set&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;set&gt;  = &lt;set&gt;.union(&lt;coll.&gt;)                   <span class="comment"># Or: &lt;set&gt; | &lt;set&gt;</span></span><br><span class="line">&lt;set&gt;  = &lt;set&gt;.intersection(&lt;coll.&gt;)            <span class="comment"># Or: &lt;set&gt; &amp; &lt;set&gt;</span></span><br><span class="line">&lt;set&gt;  = &lt;set&gt;.difference(&lt;coll.&gt;)              <span class="comment"># Or: &lt;set&gt; - &lt;set&gt;</span></span><br><span class="line">&lt;set&gt;  = &lt;set&gt;.symmetric_difference(&lt;coll.&gt;)    <span class="comment"># Or: &lt;set&gt; ^ &lt;set&gt;</span></span><br><span class="line">&lt;bool&gt; = &lt;set&gt;.issubset(&lt;coll.&gt;)                <span class="comment"># Or: &lt;set&gt; &lt;= &lt;set&gt;</span></span><br><span class="line">&lt;bool&gt; = &lt;set&gt;.issuperset(&lt;coll.&gt;)              <span class="comment"># Or: &lt;set&gt; &gt;= &lt;set&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;el&gt; = &lt;set&gt;.pop()                              <span class="comment"># Raises KeyError if empty.</span></span><br><span class="line">&lt;set&gt;.remove(&lt;el&gt;)                              <span class="comment"># Raises KeyError if missing.</span></span><br><span class="line">&lt;set&gt;.discard(&lt;el&gt;)                             <span class="comment"># Doesn't raise an error.</span></span><br></pre></td></tr></table></figure>
<h3 id="Frozen-Set"><a href="#Frozen-Set" class="headerlink" title="Frozen Set"></a>Frozen Set</h3><ul>
<li><strong>Is immutable and hashable.</strong></li>
<li><strong>That means it can be used as a key in a dictionary or as an element in a set.</strong><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;frozenset&gt; = frozenset(&lt;collection&gt;)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="Tuple"><a href="#Tuple" class="headerlink" title="Tuple"></a>Tuple</h2><p><strong>Tuple is an immutable and hashable list.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;tuple&gt; = ()</span><br><span class="line">&lt;tuple&gt; = (&lt;el&gt;, )</span><br><span class="line">&lt;tuple&gt; = (&lt;el_1&gt;, &lt;el_2&gt; [, ...])</span><br></pre></td></tr></table></figure></p>
<h3 id="Named-Tuple"><a href="#Named-Tuple" class="headerlink" title="Named Tuple"></a>Named Tuple</h3><p><strong>Tuple’s subclass with named elements.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> collections <span class="keyword">import</span> namedtuple</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>Point = namedtuple(<span class="string">'Point'</span>, <span class="string">'x y'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>p = Point(<span class="number">1</span>, y=<span class="number">2</span>)</span><br><span class="line">Point(x=<span class="number">1</span>, y=<span class="number">2</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>p[<span class="number">0</span>]</span><br><span class="line"><span class="number">1</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>p.x</span><br><span class="line"><span class="number">1</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>getattr(p, <span class="string">'y'</span>)</span><br><span class="line"><span class="number">2</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>p._fields  <span class="comment"># Or: Point._fields</span></span><br><span class="line">(<span class="string">'x'</span>, <span class="string">'y'</span>)</span><br></pre></td></tr></table></figure>
<h2 id="Range"><a href="#Range" class="headerlink" title="Range"></a>Range</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;range&gt; = range(to_exclusive)</span><br><span class="line">&lt;range&gt; = range(from_inclusive, to_exclusive)</span><br><span class="line">&lt;range&gt; = range(from_inclusive, to_exclusive, ±step_size)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">from_inclusive = &lt;range&gt;.start</span><br><span class="line">to_exclusive   = &lt;range&gt;.stop</span><br></pre></td></tr></table></figure>
<h2 id="Enumerate"><a href="#Enumerate" class="headerlink" title="Enumerate"></a>Enumerate</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> i, el <span class="keyword">in</span> enumerate(&lt;collection&gt; [, i_start]):</span><br><span class="line">    ...</span><br></pre></td></tr></table></figure>
<h2 id="Iterator"><a href="#Iterator" class="headerlink" title="Iterator"></a>Iterator</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;iter&gt; = iter(&lt;collection&gt;)                 <span class="comment"># `iter(&lt;iter&gt;)` returns unmodified iterator.</span></span><br><span class="line">&lt;iter&gt; = iter(&lt;function&gt;, to_exclusive)     <span class="comment"># A sequence of return values until 'to_exclusive'.</span></span><br><span class="line">&lt;el&gt;   = next(&lt;iter&gt; [, default])           <span class="comment"># Raises StopIteration or returns 'default' on end.</span></span><br><span class="line">&lt;list&gt; = list(&lt;iter&gt;)                       <span class="comment"># Returns a list of iterator's remaining elements.</span></span><br></pre></td></tr></table></figure>
<h3 id="Itertools"><a href="#Itertools" class="headerlink" title="Itertools"></a>Itertools</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> itertools <span class="keyword">import</span> count, repeat, cycle, chain, islice</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;iter&gt; = count(start=<span class="number">0</span>, step=<span class="number">1</span>)             <span class="comment"># Returns incremented value endlessly.</span></span><br><span class="line">&lt;iter&gt; = repeat(&lt;el&gt; [, times])             <span class="comment"># Returns element endlessly or 'times' times.</span></span><br><span class="line">&lt;iter&gt; = cycle(&lt;collection&gt;)                <span class="comment"># Repeats the sequence endlessly.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;iter&gt; = chain(&lt;coll_1&gt;, &lt;coll_2&gt; [, ...])  <span class="comment"># Empties collections in order.</span></span><br><span class="line">&lt;iter&gt; = chain.from_iterable(&lt;collection&gt;)  <span class="comment"># Empties collections inside a collection in order.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;iter&gt; = islice(&lt;collection&gt;, to_exclusive)</span><br><span class="line">&lt;iter&gt; = islice(&lt;collection&gt;, from_inclusive, to_exclusive [, +step_size])</span><br></pre></td></tr></table></figure>
<h2 id="Generator"><a href="#Generator" class="headerlink" title="Generator"></a>Generator</h2><ul>
<li><strong>Any function that contains a yield statement returns a generator.</strong></li>
<li><strong>Generators and iterators are interchangeable.</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">count</span><span class="params">(start, step)</span>:</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        <span class="keyword">yield</span> start</span><br><span class="line">        start += step</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>counter = count(<span class="number">10</span>, <span class="number">2</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>next(counter), next(counter), next(counter)</span><br><span class="line">(<span class="number">10</span>, <span class="number">12</span>, <span class="number">14</span>)</span><br></pre></td></tr></table></figure>
<h2 id="Type"><a href="#Type" class="headerlink" title="Type"></a>Type</h2><ul>
<li><strong>Everything is an object.</strong></li>
<li><strong>Every object has a type.</strong></li>
<li><strong>Type and class are synonymous.</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;type&gt; = type(&lt;el&gt;)                          <span class="comment"># Or: &lt;el&gt;.__class__</span></span><br><span class="line">&lt;bool&gt; = isinstance(&lt;el&gt;, &lt;type&gt;)            <span class="comment"># Or: issubclass(type(&lt;el&gt;), &lt;type&gt;)</span></span><br></pre></td></tr></table></figure>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>type(<span class="string">'a'</span>), <span class="string">'a'</span>.__class__, str</span><br><span class="line">(&lt;class 'str'&gt;, &lt;class 'str'&gt;, &lt;class 'str'&gt;)</span><br></pre></td></tr></table></figure>
<h4 id="Some-types-do-not-have-built-in-names-so-they-must-be-imported"><a href="#Some-types-do-not-have-built-in-names-so-they-must-be-imported" class="headerlink" title="Some types do not have built-in names, so they must be imported:"></a>Some types do not have built-in names, so they must be imported:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> types <span class="keyword">import</span> FunctionType, MethodType, LambdaType, GeneratorType</span><br></pre></td></tr></table></figure>
<h3 id="ABC"><a href="#ABC" class="headerlink" title="ABC"></a>ABC</h3><p><strong>An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> collections.abc <span class="keyword">import</span> Sequence, Collection, Iterable</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>isinstance([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], Iterable)</span><br><span class="line"><span class="literal">True</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">+------------------+------------+------------+------------+</span><br><span class="line">|                  |  Sequence  | Collection |  Iterable  |</span><br><span class="line">+------------------+------------+------------+------------+</span><br><span class="line">| list, range, str |    yes     |    yes     |    yes     |</span><br><span class="line">| dict, set        |            |    yes     |    yes     |</span><br><span class="line">| iter             |            |            |    yes     |</span><br><span class="line">+------------------+------------+------------+------------+</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> numbers <span class="keyword">import</span> Integral, Rational, Real, Complex, Number</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>isinstance(<span class="number">123</span>, Number)</span><br><span class="line"><span class="literal">True</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">+--------------------+----------+----------+----------+----------+----------+</span><br><span class="line">|                    | Integral | Rational |   Real   | Complex  |  Number  |</span><br><span class="line">+--------------------+----------+----------+----------+----------+----------+</span><br><span class="line">| int                |   yes    |   yes    |   yes    |   yes    |   yes    |</span><br><span class="line">| fractions.Fraction |          |   yes    |   yes    |   yes    |   yes    |</span><br><span class="line">| float              |          |          |   yes    |   yes    |   yes    |</span><br><span class="line">| complex            |          |          |          |   yes    |   yes    |</span><br><span class="line">| decimal.Decimal    |          |          |          |          |   yes    |</span><br><span class="line">+--------------------+----------+----------+----------+----------+----------+</span><br></pre></td></tr></table></figure>
<h2 id="String"><a href="#String" class="headerlink" title="String"></a>String</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;str&gt;  = &lt;str&gt;.strip()                       <span class="comment"># Strips all whitespace characters from both ends.</span></span><br><span class="line">&lt;str&gt;  = &lt;str&gt;.strip(<span class="string">'&lt;chars&gt;'</span>)              <span class="comment"># Strips all passed characters from both ends.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;list&gt; = &lt;str&gt;.split()                       <span class="comment"># Splits on one or more whitespace characters.</span></span><br><span class="line">&lt;list&gt; = &lt;str&gt;.split(sep=<span class="literal">None</span>, maxsplit=<span class="number">-1</span>)  <span class="comment"># Splits on 'sep' str at most 'maxsplit' times.</span></span><br><span class="line">&lt;list&gt; = &lt;str&gt;.splitlines(keepends=<span class="literal">False</span>)    <span class="comment"># Splits on line breaks. Keeps them if 'keepends'.</span></span><br><span class="line">&lt;str&gt;  = &lt;str&gt;.join(&lt;coll_of_strings&gt;)       <span class="comment"># Joins elements using string as separator.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;bool&gt; = &lt;sub_str&gt; <span class="keyword">in</span> &lt;str&gt;                  <span class="comment"># Checks if string contains a substring.</span></span><br><span class="line">&lt;bool&gt; = &lt;str&gt;.startswith(&lt;sub_str&gt;)         <span class="comment"># Pass tuple of strings for multiple options.</span></span><br><span class="line">&lt;bool&gt; = &lt;str&gt;.endswith(&lt;sub_str&gt;)           <span class="comment"># Pass tuple of strings for multiple options.</span></span><br><span class="line">&lt;int&gt;  = &lt;str&gt;.find(&lt;sub_str&gt;)               <span class="comment"># Returns start index of first match or -1.</span></span><br><span class="line">&lt;int&gt;  = &lt;str&gt;.index(&lt;sub_str&gt;)              <span class="comment"># Same but raises ValueError if missing.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;str&gt;  = &lt;str&gt;.replace(old, new [, count])   <span class="comment"># Replaces 'old' with 'new' at most 'count' times.</span></span><br><span class="line">&lt;str&gt;  = &lt;str&gt;.translate(&lt;table&gt;)            <span class="comment"># Use `str.maketrans(&lt;dict&gt;)` to generate table.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;str&gt;  = chr(&lt;int&gt;)                          <span class="comment"># Converts int to unicode char.</span></span><br><span class="line">&lt;int&gt;  = ord(&lt;str&gt;)                          <span class="comment"># Converts unicode char to int.</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Also: <code>&#39;lstrip()&#39;</code>, <code>&#39;rstrip()&#39;</code>.</strong></li>
<li><strong>Also: <code>&#39;lower()&#39;</code>, <code>&#39;upper()&#39;</code>, <code>&#39;capitalize()&#39;</code> and <code>&#39;title()&#39;</code>.</strong></li>
</ul>
<h3 id="Property-Methods"><a href="#Property-Methods" class="headerlink" title="Property Methods"></a>Property Methods</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">+---------------+----------+----------+----------+----------+----------+</span><br><span class="line">|               | [ !#$%…] | [a-zA-Z] |  [¼½¾…]  |  [²³¹…]  |  [0-9]   |</span><br><span class="line">+---------------+----------+----------+----------+----------+----------+</span><br><span class="line">| isprintable() |   yes    |   yes    |   yes    |   yes    |   yes    |</span><br><span class="line">| isalnum()     |          |   yes    |   yes    |   yes    |   yes    |</span><br><span class="line">| isnumeric()   |          |          |   yes    |   yes    |   yes    |</span><br><span class="line">| isdigit()     |          |          |          |   yes    |   yes    |</span><br><span class="line">| isdecimal()   |          |          |          |          |   yes    |</span><br><span class="line">+---------------+----------+----------+----------+----------+----------+</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Also: <code>&#39;isspace()&#39;</code> checks for <code>&#39;[ \t\n\r…]&#39;</code>.</strong></li>
</ul>
<h2 id="Regex"><a href="#Regex" class="headerlink" title="Regex"></a>Regex</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line">&lt;str&gt;   = re.sub(&lt;regex&gt;, new, text, count=<span class="number">0</span>)  <span class="comment"># Substitutes all occurrences with 'new'.</span></span><br><span class="line">&lt;list&gt;  = re.findall(&lt;regex&gt;, text)            <span class="comment"># Returns all occurrences as strings.</span></span><br><span class="line">&lt;list&gt;  = re.split(&lt;regex&gt;, text, maxsplit=<span class="number">0</span>)  <span class="comment"># Use brackets in regex to keep the matches.</span></span><br><span class="line">&lt;Match&gt; = re.search(&lt;regex&gt;, text)             <span class="comment"># Searches for first occurrence of the pattern.</span></span><br><span class="line">&lt;Match&gt; = re.match(&lt;regex&gt;, text)              <span class="comment"># Searches only at the beginning of the text.</span></span><br><span class="line">&lt;iter&gt;  = re.finditer(&lt;regex&gt;, text)           <span class="comment"># Returns all occurrences as match objects.</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Search() and match() return None if they can’t find a match.</strong></li>
<li><strong>Argument <code>&#39;flags=re.IGNORECASE&#39;</code> can be used with all functions.</strong></li>
<li><strong>Argument <code>&#39;flags=re.MULTILINE&#39;</code> makes <code>&#39;^&#39;</code> and <code>&#39;$&#39;</code> match the start/end of each line.</strong></li>
<li><strong>Argument <code>&#39;flags=re.DOTALL&#39;</code> makes dot also accept newline.</strong></li>
<li><strong>Use <code>r&#39;\1&#39;</code> or <code>&#39;\\1&#39;</code> for backreference.</strong></li>
<li><strong>Add <code>&#39;?&#39;</code> after an operator to make it non-greedy.</strong></li>
</ul>
<h3 id="Match-Object"><a href="#Match-Object" class="headerlink" title="Match Object"></a>Match Object</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;str&gt;   = &lt;Match&gt;.group()                      <span class="comment"># Returns whole match. Also group(0).</span></span><br><span class="line">&lt;str&gt;   = &lt;Match&gt;.group(<span class="number">1</span>)                     <span class="comment"># Returns part in first bracket.</span></span><br><span class="line">&lt;tuple&gt; = &lt;Match&gt;.groups()                     <span class="comment"># Returns all bracketed parts.</span></span><br><span class="line">&lt;int&gt;   = &lt;Match&gt;.start()                      <span class="comment"># Returns start index of a match.</span></span><br><span class="line">&lt;int&gt;   = &lt;Match&gt;.end()                        <span class="comment"># Returns exclusive end index of a match.</span></span><br></pre></td></tr></table></figure>
<h3 id="Special-Sequences"><a href="#Special-Sequences" class="headerlink" title="Special Sequences"></a>Special Sequences</h3><ul>
<li><strong>By default digits, whitespaces and alphanumerics from all alphabets are matched, unless <code>&#39;flags=re.ASCII&#39;</code> argument is used.</strong></li>
<li><strong>Use capital letter for negation.</strong><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'\d'</span> == <span class="string">'[0-9]'</span>                                <span class="comment"># Matches any digit.</span></span><br><span class="line"><span class="string">'\s'</span> == <span class="string">'[ \t\n\r\f\v]'</span>                        <span class="comment"># Matches any whitespace.</span></span><br><span class="line"><span class="string">'\w'</span> == <span class="string">'[a-zA-Z0-9_]'</span>                         <span class="comment"># Matches any alphanumeric.</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="Format"><a href="#Format" class="headerlink" title="Format"></a>Format</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;str&gt; = <span class="string">f'<span class="subst">&#123;&lt;el_1&gt;&#125;</span>, <span class="subst">&#123;&lt;el_2&gt;&#125;</span>'</span></span><br><span class="line">&lt;str&gt; = <span class="string">'&#123;&#125;, &#123;&#125;'</span>.format(&lt;el_1&gt;, &lt;el_2&gt;)</span><br></pre></td></tr></table></figure>
<h3 id="Attributes"><a href="#Attributes" class="headerlink" title="Attributes"></a>Attributes</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> collections <span class="keyword">import</span> namedtuple</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>Person = namedtuple(<span class="string">'Person'</span>, <span class="string">'name height'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>person = Person(<span class="string">'Jean-Luc'</span>, <span class="number">187</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">f'<span class="subst">&#123;person.height&#125;</span>'</span></span><br><span class="line"><span class="string">'187'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">'&#123;p.height&#125;'</span>.format(p=person)</span><br><span class="line"><span class="string">'187'</span></span><br></pre></td></tr></table></figure>
<h3 id="General-Options"><a href="#General-Options" class="headerlink" title="General Options"></a>General Options</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;&lt;el&gt;:&lt;<span class="number">10</span>&#125;                                     <span class="comment"># '&lt;el&gt;      '</span></span><br><span class="line">&#123;&lt;el&gt;:^<span class="number">10</span>&#125;                                     <span class="comment"># '   &lt;el&gt;   '</span></span><br><span class="line">&#123;&lt;el&gt;:&gt;<span class="number">10</span>&#125;                                     <span class="comment"># '      &lt;el&gt;'</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#123;&lt;el&gt;:.&lt;<span class="number">10</span>&#125;                                    <span class="comment"># '&lt;el&gt;......'</span></span><br><span class="line">&#123;&lt;el&gt;:&lt;<span class="number">0</span>&#125;                                      <span class="comment"># '&lt;el&gt;'</span></span><br></pre></td></tr></table></figure>
<h3 id="Strings"><a href="#Strings" class="headerlink" title="Strings"></a>Strings</h3><p><strong><code>&#39;!r&#39;</code> calls object’s <a href="#class">repr()</a> method, instead of <a href="#class">str()</a>, to get a string.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="string">'abcde'</span>!r:&lt;<span class="number">10</span>&#125;                                <span class="comment"># "'abcde'   "</span></span><br><span class="line">&#123;<span class="string">'abcde'</span>:<span class="number">.3</span>&#125;                                   <span class="comment"># 'abc'</span></span><br><span class="line">&#123;<span class="string">'abcde'</span>:<span class="number">10.3</span>&#125;                                 <span class="comment"># 'abc       '</span></span><br></pre></td></tr></table></figure></p>
<h3 id="Numbers"><a href="#Numbers" class="headerlink" title="Numbers"></a>Numbers</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123; <span class="number">123456</span>:<span class="number">10</span>,&#125;                                  <span class="comment"># '   123,456'</span></span><br><span class="line">&#123; <span class="number">123456</span>:<span class="number">10</span>_&#125;                                  <span class="comment"># '   123_456'</span></span><br><span class="line">&#123; <span class="number">123456</span>:+<span class="number">10</span>&#125;                                  <span class="comment"># '   +123456'</span></span><br><span class="line">&#123;<span class="number">-123456</span>:=<span class="number">10</span>&#125;                                  <span class="comment"># '-   123456'</span></span><br><span class="line">&#123; <span class="number">123456</span>: &#125;                                    <span class="comment"># ' 123456'</span></span><br><span class="line">&#123;<span class="number">-123456</span>: &#125;                                    <span class="comment"># '-123456'</span></span><br></pre></td></tr></table></figure>
<h3 id="Floats"><a href="#Floats" class="headerlink" title="Floats"></a>Floats</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="number">1.23456</span>:<span class="number">10.3</span>&#125;                                 <span class="comment"># '      1.23'</span></span><br><span class="line">&#123;<span class="number">1.23456</span>:<span class="number">10.3</span>f&#125;                                <span class="comment"># '     1.235'</span></span><br><span class="line">&#123;<span class="number">1.23456</span>:<span class="number">10.3</span>e&#125;                                <span class="comment"># ' 1.235e+00'</span></span><br><span class="line">&#123;<span class="number">1.23456</span>:<span class="number">10.3</span>%&#125;                                <span class="comment"># '  123.456%'</span></span><br></pre></td></tr></table></figure>
<h4 id="Comparison-of-float-presentation-types"><a href="#Comparison-of-float-presentation-types" class="headerlink" title="Comparison of float presentation types:"></a>Comparison of float presentation types:</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">+---------------+-----------------+-----------------+-----------------+-----------------+</span><br><span class="line">|               |    &#123;&lt;float&gt;&#125;    |   &#123;&lt;float&gt;:f&#125;   |   &#123;&lt;float&gt;:e&#125;   |   &#123;&lt;float&gt;:%&#125;   |</span><br><span class="line">+---------------+-----------------+-----------------+-----------------+-----------------+</span><br><span class="line">|   0.000056789 |    &apos;5.6789e-05&apos; |     &apos;0.000057&apos;  |  &apos;5.678900e-05&apos; |     &apos;0.005679%&apos; |</span><br><span class="line">|   0.00056789  |    &apos;0.00056789&apos; |     &apos;0.000568&apos;  |  &apos;5.678900e-04&apos; |     &apos;0.056789%&apos; |</span><br><span class="line">|   0.0056789   |    &apos;0.0056789&apos;  |     &apos;0.005679&apos;  |  &apos;5.678900e-03&apos; |     &apos;0.567890%&apos; |</span><br><span class="line">|   0.056789    |    &apos;0.056789&apos;   |     &apos;0.056789&apos;  |  &apos;5.678900e-02&apos; |     &apos;5.678900%&apos; |</span><br><span class="line">|   0.56789     |    &apos;0.56789&apos;    |     &apos;0.567890&apos;  |  &apos;5.678900e-01&apos; |    &apos;56.789000%&apos; |</span><br><span class="line">|   5.6789      |    &apos;5.6789&apos;     |     &apos;5.678900&apos;  |  &apos;5.678900e+00&apos; |   &apos;567.890000%&apos; |</span><br><span class="line">|  56.789       |   &apos;56.789&apos;      |    &apos;56.789000&apos;  |  &apos;5.678900e+01&apos; |  &apos;5678.900000%&apos; |</span><br><span class="line">| 567.89        |  &apos;567.89&apos;       |   &apos;567.890000&apos;  |  &apos;5.678900e+02&apos; | &apos;56789.000000%&apos; |</span><br><span class="line">+---------------+-----------------+-----------------+-----------------+-----------------+</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">+---------------+-----------------+-----------------+-----------------+-----------------+</span><br><span class="line">|               |   &#123;&lt;float&gt;:.2&#125;  |  &#123;&lt;float&gt;:.2f&#125;  |  &#123;&lt;float&gt;:.2e&#125;  |  &#123;&lt;float&gt;:.2%&#125;  |</span><br><span class="line">+---------------+-----------------+-----------------+-----------------+-----------------+</span><br><span class="line">|   0.000056789 |    &apos;5.7e-05&apos;    |       &apos;0.00&apos;    |    &apos;5.68e-05&apos;   |       &apos;0.01%&apos;   |</span><br><span class="line">|   0.00056789  |    &apos;0.00057&apos;    |       &apos;0.00&apos;    |    &apos;5.68e-04&apos;   |       &apos;0.06%&apos;   |</span><br><span class="line">|   0.0056789   |    &apos;0.0057&apos;     |       &apos;0.01&apos;    |    &apos;5.68e-03&apos;   |       &apos;0.57%&apos;   |</span><br><span class="line">|   0.056789    |    &apos;0.057&apos;      |       &apos;0.06&apos;    |    &apos;5.68e-02&apos;   |       &apos;5.68%&apos;   |</span><br><span class="line">|   0.56789     |    &apos;0.57&apos;       |       &apos;0.57&apos;    |    &apos;5.68e-01&apos;   |      &apos;56.79%&apos;   |</span><br><span class="line">|   5.6789      |    &apos;5.7&apos;        |       &apos;5.68&apos;    |    &apos;5.68e+00&apos;   |     &apos;567.89%&apos;   |</span><br><span class="line">|  56.789       |    &apos;5.7e+01&apos;    |      &apos;56.79&apos;    |    &apos;5.68e+01&apos;   |    &apos;5678.90%&apos;   |</span><br><span class="line">| 567.89        |    &apos;5.7e+02&apos;    |     &apos;567.89&apos;    |    &apos;5.68e+02&apos;   |   &apos;56789.00%&apos;   |</span><br><span class="line">+---------------+-----------------+-----------------+-----------------+-----------------+</span><br></pre></td></tr></table></figure>
<h3 id="Ints"><a href="#Ints" class="headerlink" title="Ints"></a>Ints</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="number">90</span>:c&#125;                                <span class="comment"># 'Z'</span></span><br><span class="line">&#123;<span class="number">90</span>:b&#125;                                <span class="comment"># '1011010'</span></span><br><span class="line">&#123;<span class="number">90</span>:X&#125;                                <span class="comment"># '5A'</span></span><br></pre></td></tr></table></figure>
<h2 id="Numbers-1"><a href="#Numbers-1" class="headerlink" title="Numbers"></a>Numbers</h2><h3 id="Types"><a href="#Types" class="headerlink" title="Types"></a>Types</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;int&gt;      = int(&lt;float/str/bool&gt;)    <span class="comment"># Or: math.floor(&lt;float&gt;)</span></span><br><span class="line">&lt;float&gt;    = float(&lt;int/str/bool&gt;)    <span class="comment"># Or: &lt;real&gt;e±&lt;int&gt;</span></span><br><span class="line">&lt;complex&gt;  = complex(real=<span class="number">0</span>, imag=<span class="number">0</span>)  <span class="comment"># Or: &lt;real&gt; ± &lt;real&gt;j</span></span><br><span class="line">&lt;Fraction&gt; = fractions.Fraction(numerator=<span class="number">0</span>, denominator=<span class="number">1</span>)</span><br><span class="line">&lt;Decimal&gt;  = decimal.Decimal(&lt;str/int/float&gt;)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong><code>&#39;int(&lt;str&gt;)&#39;</code> and <code>&#39;float(&lt;str&gt;)&#39;</code> raise ValueError on malformed strings.</strong></li>
<li><strong>Decimal numbers can be represented exactly, unlike floats where <code>&#39;1.1 + 2.2 != 3.3&#39;</code>.</strong></li>
<li><strong>Precision of decimal operations is set with: <code>&#39;decimal.getcontext().prec = &lt;int&gt;&#39;</code>.</strong></li>
</ul>
<h3 id="Basic-Functions"><a href="#Basic-Functions" class="headerlink" title="Basic Functions"></a>Basic Functions</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;num&gt; = pow(&lt;num&gt;, &lt;num&gt;)             <span class="comment"># Or: &lt;num&gt; ** &lt;num&gt;</span></span><br><span class="line">&lt;num&gt; = abs(&lt;num&gt;)                    <span class="comment"># &lt;float&gt; = abs(&lt;complex&gt;)</span></span><br><span class="line">&lt;num&gt; = round(&lt;num&gt; [, ±ndigits])     <span class="comment"># `round(126, -1) == 130`</span></span><br></pre></td></tr></table></figure>
<h3 id="Math"><a href="#Math" class="headerlink" title="Math"></a>Math</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> math <span class="keyword">import</span> e, pi, inf, nan</span><br><span class="line"><span class="keyword">from</span> math <span class="keyword">import</span> cos, acos, sin, asin, tan, atan, degrees, radians</span><br><span class="line"><span class="keyword">from</span> math <span class="keyword">import</span> log, log10, log2</span><br></pre></td></tr></table></figure>
<h3 id="Statistics"><a href="#Statistics" class="headerlink" title="Statistics"></a>Statistics</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> statistics <span class="keyword">import</span> mean, median, variance, pvariance, pstdev</span><br></pre></td></tr></table></figure>
<h3 id="Random"><a href="#Random" class="headerlink" title="Random"></a>Random</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> random <span class="keyword">import</span> random, randint, choice, shuffle</span><br><span class="line">&lt;float&gt; = random()</span><br><span class="line">&lt;int&gt;   = randint(from_inclusive, to_inclusive)</span><br><span class="line">&lt;el&gt;    = choice(&lt;list&gt;)</span><br><span class="line">shuffle(&lt;list&gt;)</span><br></pre></td></tr></table></figure>
<h3 id="Bin-Hex"><a href="#Bin-Hex" class="headerlink" title="Bin, Hex"></a>Bin, Hex</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;int&gt;     = <span class="number">0</span>b&lt;bin&gt;                   <span class="comment"># Or: 0x&lt;hex&gt;</span></span><br><span class="line">&lt;int&gt;     = int(<span class="string">'&lt;bin&gt;'</span>, <span class="number">2</span>)           <span class="comment"># Or: int('&lt;hex&gt;', 16)</span></span><br><span class="line">&lt;int&gt;     = int(<span class="string">'0b&lt;bin&gt;'</span>, <span class="number">0</span>)         <span class="comment"># Or: int('0x&lt;hex&gt;', 0)</span></span><br><span class="line"><span class="string">'0b&lt;bin&gt;'</span> = bin(&lt;int&gt;)                <span class="comment"># Or: '0x&lt;hex&gt;' = hex(&lt;int&gt;)</span></span><br></pre></td></tr></table></figure>
<h3 id="Bitwise-Operators"><a href="#Bitwise-Operators" class="headerlink" title="Bitwise Operators"></a>Bitwise Operators</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;int&gt;     = &lt;int&gt; &amp; &lt;int&gt;             <span class="comment"># And</span></span><br><span class="line">&lt;int&gt;     = &lt;int&gt; | &lt;int&gt;             <span class="comment"># Or</span></span><br><span class="line">&lt;int&gt;     = &lt;int&gt; ^ &lt;int&gt;             <span class="comment"># Xor (0 if both bits equal)</span></span><br><span class="line">&lt;int&gt;     = &lt;int&gt; &lt;&lt; n_bits           <span class="comment"># Shift left</span></span><br><span class="line">&lt;int&gt;     = &lt;int&gt; &gt;&gt; n_bits           <span class="comment"># Shift right</span></span><br><span class="line">&lt;int&gt;     = ~&lt;int&gt;                    <span class="comment"># Compliment (flips bits)</span></span><br></pre></td></tr></table></figure>
<h2 id="Combinatorics"><a href="#Combinatorics" class="headerlink" title="Combinatorics"></a>Combinatorics</h2><ul>
<li><strong>Every function returns an iterator.</strong></li>
<li><strong>If you want to print the iterator, you need to pass it to the list() function!</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> itertools <span class="keyword">import</span> product, combinations, combinations_with_replacement, permutations</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>product([<span class="number">0</span>, <span class="number">1</span>], repeat=<span class="number">3</span>)</span><br><span class="line">[(<span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>), (<span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>), (<span class="number">0</span>, <span class="number">1</span>, <span class="number">0</span>), (<span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>),</span><br><span class="line"> (<span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>), (<span class="number">1</span>, <span class="number">0</span>, <span class="number">1</span>), (<span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>), (<span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>)]</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>product(<span class="string">'ab'</span>, <span class="string">'12'</span>)</span><br><span class="line">[(<span class="string">'a'</span>, <span class="string">'1'</span>), (<span class="string">'a'</span>, <span class="string">'2'</span>),</span><br><span class="line"> (<span class="string">'b'</span>, <span class="string">'1'</span>), (<span class="string">'b'</span>, <span class="string">'2'</span>)]</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>combinations(<span class="string">'abc'</span>, <span class="number">2</span>)</span><br><span class="line">[(<span class="string">'a'</span>, <span class="string">'b'</span>), (<span class="string">'a'</span>, <span class="string">'c'</span>), (<span class="string">'b'</span>, <span class="string">'c'</span>)]</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>combinations_with_replacement(<span class="string">'abc'</span>, <span class="number">2</span>)</span><br><span class="line">[(<span class="string">'a'</span>, <span class="string">'a'</span>), (<span class="string">'a'</span>, <span class="string">'b'</span>), (<span class="string">'a'</span>, <span class="string">'c'</span>),</span><br><span class="line"> (<span class="string">'b'</span>, <span class="string">'b'</span>), (<span class="string">'b'</span>, <span class="string">'c'</span>),</span><br><span class="line"> (<span class="string">'c'</span>, <span class="string">'c'</span>)]</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>permutations(<span class="string">'abc'</span>, <span class="number">2</span>)</span><br><span class="line">[(<span class="string">'a'</span>, <span class="string">'b'</span>), (<span class="string">'a'</span>, <span class="string">'c'</span>),</span><br><span class="line"> (<span class="string">'b'</span>, <span class="string">'a'</span>), (<span class="string">'b'</span>, <span class="string">'c'</span>),</span><br><span class="line"> (<span class="string">'c'</span>, <span class="string">'a'</span>), (<span class="string">'c'</span>, <span class="string">'b'</span>)]</span><br></pre></td></tr></table></figure>
<h2 id="Datetime"><a href="#Datetime" class="headerlink" title="Datetime"></a>Datetime</h2><ul>
<li><strong>Module ‘datetime’ provides ‘date’ <code>&lt;D&gt;</code>, ‘time’ <code>&lt;T&gt;</code>, ‘datetime’ <code>&lt;DT&gt;</code> and ‘timedelta’ <code>&lt;TD&gt;</code> classes. All are immutable and hashable.</strong></li>
<li><strong>Time and datetime can be ‘aware’ <code>&lt;a&gt;</code>, meaning they have defined timezone, or ‘naive’ <code>&lt;n&gt;</code>, meaning they don’t.</strong></li>
<li><strong>If object is naive, it is presumed to be in the system’s timezone.</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> datetime <span class="keyword">import</span> date, time, datetime, timedelta</span><br><span class="line"><span class="keyword">from</span> dateutil.tz <span class="keyword">import</span> UTC, tzlocal, gettz, resolve_imaginary</span><br></pre></td></tr></table></figure>
<h3 id="Constructors"><a href="#Constructors" class="headerlink" title="Constructors"></a>Constructors</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;D&gt;  = date(year, month, day)</span><br><span class="line">&lt;T&gt;  = time(hour=<span class="number">0</span>, minute=<span class="number">0</span>, second=<span class="number">0</span>, microsecond=<span class="number">0</span>, tzinfo=<span class="literal">None</span>, fold=<span class="number">0</span>)</span><br><span class="line">&lt;DT&gt; = datetime(year, month, day, hour=<span class="number">0</span>, minute=<span class="number">0</span>, second=<span class="number">0</span>, ...)</span><br><span class="line">&lt;TD&gt; = timedelta(days=<span class="number">0</span>, seconds=<span class="number">0</span>, microseconds=<span class="number">0</span>, milliseconds=<span class="number">0</span>,</span><br><span class="line">                 minutes=<span class="number">0</span>, hours=<span class="number">0</span>, weeks=<span class="number">0</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Use <code>&#39;&lt;D/DT&gt;.weekday()&#39;</code> to get the day of the week (Mon == 0).</strong></li>
<li><strong><code>&#39;fold=1&#39;</code> means second pass in case of time jumping back for one hour.</strong></li>
<li><strong><code>&#39;&lt;DTa&gt; = resolve_imaginary(&lt;DTa&gt;)&#39;</code> fixes DTs that fall into missing hour.</strong></li>
</ul>
<h3 id="Now"><a href="#Now" class="headerlink" title="Now"></a>Now</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;D/DTn&gt;  = D/DT.today()                     <span class="comment"># Current local date or naive datetime.</span></span><br><span class="line">&lt;DTn&gt;    = DT.utcnow()                      <span class="comment"># Naive datetime from current UTC time.</span></span><br><span class="line">&lt;DTa&gt;    = DT.now(&lt;tzinfo&gt;)                 <span class="comment"># Aware datetime from current tz time.</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>To extract time use <code>&#39;&lt;DTn&gt;.time()&#39;</code>, <code>&#39;&lt;DTa&gt;.time()&#39;</code> or <code>&#39;&lt;DTa&gt;.timetz()&#39;</code>.</strong></li>
</ul>
<h3 id="Timezone"><a href="#Timezone" class="headerlink" title="Timezone"></a>Timezone</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;tzinfo&gt; = UTC                              <span class="comment"># UTC timezone. London without DST.</span></span><br><span class="line">&lt;tzinfo&gt; = tzlocal()                        <span class="comment"># Local timezone. Also gettz().</span></span><br><span class="line">&lt;tzinfo&gt; = gettz(<span class="string">'&lt;Cont.&gt;/&lt;City&gt;'</span>)          <span class="comment"># 'Continent/City_Name' timezone or None.</span></span><br><span class="line">&lt;DTa&gt;    = &lt;DT&gt;.astimezone(&lt;tzinfo&gt;)        <span class="comment"># Datetime, converted to passed timezone.</span></span><br><span class="line">&lt;Ta/DTa&gt; = &lt;T/DT&gt;.replace(tzinfo=&lt;tzinfo&gt;)  <span class="comment"># Unconverted object with new timezone.</span></span><br></pre></td></tr></table></figure>
<h3 id="Encode"><a href="#Encode" class="headerlink" title="Encode"></a>Encode</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;D/T/DT&gt; = D/T/DT.fromisoformat(<span class="string">'&lt;iso&gt;'</span>)    <span class="comment"># Object from ISO string. Raises ValueError.</span></span><br><span class="line">&lt;DT&gt;     = DT.strptime(&lt;str&gt;, <span class="string">'&lt;format&gt;'</span>)   <span class="comment"># Datetime from str, according to format.</span></span><br><span class="line">&lt;D/DTn&gt;  = D/DT.fromordinal(&lt;int&gt;)          <span class="comment"># D/DTn from days since Christ, at midnight.</span></span><br><span class="line">&lt;DTn&gt;    = DT.fromtimestamp(&lt;real&gt;)         <span class="comment"># Local time DTn from seconds since Epoch.</span></span><br><span class="line">&lt;DTa&gt;    = DT.fromtimestamp(&lt;real&gt;, &lt;tz.&gt;)  <span class="comment"># Aware datetime from seconds since Epoch.</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>ISO strings come in following forms: <code>&#39;YYYY-MM-DD&#39;</code>, <code>&#39;HH:MM:SS.ffffff[±&lt;offset&gt;]&#39;</code>, or both separated by a space or a <code>&#39;T&#39;</code>. Offset is formatted as: <code>&#39;HH:MM&#39;</code>.</strong></li>
<li><strong>On Unix systems Epoch is <code>&#39;1970-01-01 00:00 UTC&#39;</code>, <code>&#39;1970-01-01 01:00 CET&#39;</code>, …</strong></li>
</ul>
<h3 id="Decode"><a href="#Decode" class="headerlink" title="Decode"></a>Decode</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;str&gt;    = &lt;D/T/DT&gt;.isoformat(sep=<span class="string">'T'</span>)      <span class="comment"># Also timespec='auto/hours/minutes/seconds'.</span></span><br><span class="line">&lt;str&gt;    = &lt;D/T/DT&gt;.strftime(<span class="string">'&lt;format&gt;'</span>)    <span class="comment"># Custom string representation.</span></span><br><span class="line">&lt;int&gt;    = &lt;D/DT&gt;.toordinal()               <span class="comment"># Days since Christ, ignoring time and tz.</span></span><br><span class="line">&lt;float&gt;  = &lt;DTn&gt;.timestamp()                <span class="comment"># Seconds since Epoch from DTn in local time.</span></span><br><span class="line">&lt;float&gt;  = &lt;DTa&gt;.timestamp()                <span class="comment"># Seconds since Epoch from DTa.</span></span><br></pre></td></tr></table></figure>
<h3 id="Format-1"><a href="#Format-1" class="headerlink" title="Format"></a>Format</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> datetime <span class="keyword">import</span> datetime</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>dt = datetime.strptime(<span class="string">'2015-05-14 23:39:00.00 +0200'</span>, <span class="string">'%Y-%m-%d %H:%M:%S.%f %z'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>dt.strftime(<span class="string">"%A, %dth of %B '%y, %I:%M%p %Z"</span>)</span><br><span class="line"><span class="string">"Thursday, 14th of May '15, 11:39PM UTC+02:00"</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>When parsing, <code>&#39;%z&#39;</code> also accepts <code>&#39;±HH:MM&#39;</code>.</strong></li>
<li><strong>For abbreviated weekday and month use <code>&#39;%a&#39;</code> and <code>&#39;%b&#39;</code>.</strong></li>
</ul>
<h3 id="Arithmetics"><a href="#Arithmetics" class="headerlink" title="Arithmetics"></a>Arithmetics</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;D/DT&gt;   = &lt;D/DT&gt; ± &lt;TD&gt;                    <span class="comment"># Result can fall into missing hour.</span></span><br><span class="line">&lt;TD&gt;     = &lt;D/DT&gt; - &lt;D/DT&gt;                  <span class="comment"># Ignores time jumps if they share non tzlocal tz.</span></span><br><span class="line">&lt;TD&gt;     = &lt;DT_UTC&gt; - &lt;DT_UTC&gt;              <span class="comment"># Convert DTs to UTC to get the actual delta.</span></span><br></pre></td></tr></table></figure>
<h2 id="Arguments"><a href="#Arguments" class="headerlink" title="Arguments"></a>Arguments</h2><h3 id="Inside-Function-Call"><a href="#Inside-Function-Call" class="headerlink" title="Inside Function Call"></a>Inside Function Call</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;function&gt;(&lt;positional_args&gt;)                  <span class="comment"># f(0, 0)</span></span><br><span class="line">&lt;function&gt;(&lt;keyword_args&gt;)                     <span class="comment"># f(x=0, y=0)</span></span><br><span class="line">&lt;function&gt;(&lt;positional_args&gt;, &lt;keyword_args&gt;)  <span class="comment"># f(0, y=0)</span></span><br></pre></td></tr></table></figure>
<h3 id="Inside-Function-Definition"><a href="#Inside-Function-Definition" class="headerlink" title="Inside Function Definition"></a>Inside Function Definition</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(&lt;nondefault_args&gt;)</span>:</span>                      <span class="comment"># def f(x, y):</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(&lt;default_args&gt;)</span>:</span>                         <span class="comment"># def f(x=0, y=0):</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(&lt;nondefault_args&gt;, &lt;default_args&gt;)</span>:</span>      <span class="comment"># def f(x, y=0):</span></span><br></pre></td></tr></table></figure>
<h2 id="Splat-Operator"><a href="#Splat-Operator" class="headerlink" title="Splat Operator"></a>Splat Operator</h2><h3 id="Inside-Function-Call-1"><a href="#Inside-Function-Call-1" class="headerlink" title="Inside Function Call"></a>Inside Function Call</h3><p><strong>Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">args   = (<span class="number">1</span>, <span class="number">2</span>)</span><br><span class="line">kwargs = &#123;<span class="string">'x'</span>: <span class="number">3</span>, <span class="string">'y'</span>: <span class="number">4</span>, <span class="string">'z'</span>: <span class="number">5</span>&#125;</span><br><span class="line">func(*args, **kwargs)</span><br></pre></td></tr></table></figure></p>
<h4 id="Is-the-same-as"><a href="#Is-the-same-as" class="headerlink" title="Is the same as:"></a>Is the same as:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">func(<span class="number">1</span>, <span class="number">2</span>, x=<span class="number">3</span>, y=<span class="number">4</span>, z=<span class="number">5</span>)</span><br></pre></td></tr></table></figure>
<h3 id="Inside-Function-Definition-1"><a href="#Inside-Function-Definition-1" class="headerlink" title="Inside Function Definition"></a>Inside Function Definition</h3><p><strong>Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span><span class="params">(*a)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> sum(a)</span><br></pre></td></tr></table></figure></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>add(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line"><span class="number">6</span></span><br></pre></td></tr></table></figure>
<h4 id="Legal-argument-combinations"><a href="#Legal-argument-combinations" class="headerlink" title="Legal argument combinations:"></a>Legal argument combinations:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(x, y, z)</span>:</span>                <span class="comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(*, x, y, z)</span>:</span>             <span class="comment"># f(x=1, y=2, z=3)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(x, *, y, z)</span>:</span>             <span class="comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(x, y, *, z)</span>:</span>             <span class="comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(*args)</span>:</span>                  <span class="comment"># f(1, 2, 3)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(x, *args)</span>:</span>               <span class="comment"># f(1, 2, 3)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(*args, z)</span>:</span>               <span class="comment"># f(1, 2, z=3)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(x, *args, z)</span>:</span>            <span class="comment"># f(1, 2, z=3)</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(**kwargs)</span>:</span>               <span class="comment"># f(x=1, y=2, z=3)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(x, **kwargs)</span>:</span>            <span class="comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(*, x, **kwargs)</span>:</span>         <span class="comment"># f(x=1, y=2, z=3)</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(*args, **kwargs)</span>:</span>        <span class="comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(x, *args, **kwargs)</span>:</span>     <span class="comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(*args, y, **kwargs)</span>:</span>     <span class="comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">(x, *args, z, **kwargs)</span>:</span>  <span class="comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)</span></span><br></pre></td></tr></table></figure>
<h3 id="Other-Uses"><a href="#Other-Uses" class="headerlink" title="Other Uses"></a>Other Uses</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;list&gt;  = [*&lt;collection&gt; [, ...]]</span><br><span class="line">&lt;set&gt;   = &#123;*&lt;collection&gt; [, ...]&#125;</span><br><span class="line">&lt;tuple&gt; = (*&lt;collection&gt;, [...])</span><br><span class="line">&lt;dict&gt;  = &#123;**&lt;dict&gt; [, ...]&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">head, *body, tail = &lt;collection&gt;</span><br></pre></td></tr></table></figure>
<h2 id="Inline"><a href="#Inline" class="headerlink" title="Inline"></a>Inline</h2><h3 id="Lambda"><a href="#Lambda" class="headerlink" title="Lambda"></a>Lambda</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;function&gt; = <span class="keyword">lambda</span>: &lt;return_value&gt;</span><br><span class="line">&lt;function&gt; = <span class="keyword">lambda</span> &lt;argument_1&gt;, &lt;argument_2&gt;: &lt;return_value&gt;</span><br></pre></td></tr></table></figure>
<h3 id="Comprehension"><a href="#Comprehension" class="headerlink" title="Comprehension"></a>Comprehension</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;list&gt; = [i+<span class="number">1</span> <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>)]                   <span class="comment"># [1, 2, ..., 10]</span></span><br><span class="line">&lt;set&gt;  = &#123;i <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>) <span class="keyword">if</span> i &gt; <span class="number">5</span>&#125;            <span class="comment"># &#123;6, 7, 8, 9&#125;</span></span><br><span class="line">&lt;iter&gt; = (i+<span class="number">5</span> <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>))                   <span class="comment"># (5, 6, ..., 14)</span></span><br><span class="line">&lt;dict&gt; = &#123;i: i*<span class="number">2</span> <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>)&#125;                <span class="comment"># &#123;0: 0, 1: 2, ..., 9: 18&#125;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">out = [i+j <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>) <span class="keyword">for</span> j <span class="keyword">in</span> range(<span class="number">10</span>)]</span><br></pre></td></tr></table></figure>
<h4 id="Is-the-same-as-1"><a href="#Is-the-same-as-1" class="headerlink" title="Is the same as:"></a>Is the same as:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">out = []</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>):</span><br><span class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> range(<span class="number">10</span>):</span><br><span class="line">        out.append(i+j)</span><br></pre></td></tr></table></figure>
<h3 id="Map-Filter-Reduce"><a href="#Map-Filter-Reduce" class="headerlink" title="Map, Filter, Reduce"></a>Map, Filter, Reduce</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> reduce</span><br><span class="line">&lt;iter&gt; = map(<span class="keyword">lambda</span> x: x + <span class="number">1</span>, range(<span class="number">10</span>))            <span class="comment"># (1, 2, ..., 10)</span></span><br><span class="line">&lt;iter&gt; = filter(<span class="keyword">lambda</span> x: x &gt; <span class="number">5</span>, range(<span class="number">10</span>))         <span class="comment"># (6, 7, 8, 9)</span></span><br><span class="line">&lt;obj&gt;  = reduce(<span class="keyword">lambda</span> out, x: out + x, range(<span class="number">10</span>))  <span class="comment"># 45</span></span><br></pre></td></tr></table></figure>
<h3 id="Any-All"><a href="#Any-All" class="headerlink" title="Any, All"></a>Any, All</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;bool&gt; = any(&lt;collection&gt;)                          <span class="comment"># False if empty.</span></span><br><span class="line">&lt;bool&gt; = all(el[<span class="number">1</span>] <span class="keyword">for</span> el <span class="keyword">in</span> &lt;collection&gt;)          <span class="comment"># True if empty.</span></span><br></pre></td></tr></table></figure>
<h3 id="If-Else"><a href="#If-Else" class="headerlink" title="If - Else"></a>If - Else</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;obj&gt; = &lt;expression_if_true&gt; <span class="keyword">if</span> &lt;condition&gt; <span class="keyword">else</span> &lt;expression_if_false&gt;</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>[a <span class="keyword">if</span> a <span class="keyword">else</span> <span class="string">'zero'</span> <span class="keyword">for</span> a <span class="keyword">in</span> (<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)]</span><br><span class="line">[<span class="string">'zero'</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br></pre></td></tr></table></figure>
<h3 id="Namedtuple-Enum-Dataclass"><a href="#Namedtuple-Enum-Dataclass" class="headerlink" title="Namedtuple, Enum, Dataclass"></a>Namedtuple, Enum, Dataclass</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> namedtuple</span><br><span class="line">Point     = namedtuple(<span class="string">'Point'</span>, <span class="string">'x y'</span>)</span><br><span class="line">point     = Point(<span class="number">0</span>, <span class="number">0</span>)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> enum <span class="keyword">import</span> Enum</span><br><span class="line">Direction = Enum(<span class="string">'Direction'</span>, <span class="string">'n e s w'</span>)</span><br><span class="line">direction = Direction.n</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> dataclasses <span class="keyword">import</span> make_dataclass</span><br><span class="line">Creature  = make_dataclass(<span class="string">'Creature'</span>, [<span class="string">'location'</span>, <span class="string">'direction'</span>])</span><br><span class="line">creature  = Creature(Point(<span class="number">0</span>, <span class="number">0</span>), Direction.n)</span><br></pre></td></tr></table></figure>
<h2 id="Closure"><a href="#Closure" class="headerlink" title="Closure"></a>Closure</h2><p><strong>We have a closure in Python when:</strong></p>
<ul>
<li><strong>A nested function references a value of its enclosing function and then</strong></li>
<li><strong>the enclosing function returns the nested function.</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_multiplier</span><span class="params">(a)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">out</span><span class="params">(b)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> a * b</span><br><span class="line">    <span class="keyword">return</span> out</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>multiply_by_3 = get_multiplier(<span class="number">3</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>multiply_by_3(<span class="number">10</span>)</span><br><span class="line"><span class="number">30</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>If multiple nested functions within enclosing function reference the same value, that value gets shared.</strong></li>
<li><strong>To dynamically access function’s first free variable use <code>&#39;&lt;function&gt;.__closure__[0].cell_contents&#39;</code>.</strong></li>
</ul>
<h3 id="Partial"><a href="#Partial" class="headerlink" title="Partial"></a>Partial</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> partial</span><br><span class="line">&lt;function&gt; = partial(&lt;function&gt; [, &lt;arg_1&gt;, &lt;arg_2&gt;, ...])</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> operator <span class="keyword">as</span> op</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>multiply_by_3 = partial(op.mul, <span class="number">3</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>multiply_by_3(<span class="number">10</span>)</span><br><span class="line"><span class="number">30</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Partial is also useful in cases when function needs to be passed as an argument, because it enables us to set its arguments beforehand.</strong></li>
<li><strong>A few examples being: <code>&#39;defaultdict(&lt;function&gt;)&#39;</code>, <code>&#39;iter(&lt;function&gt;, to_exclusive)&#39;</code> and dataclass’s <code>&#39;field(default_factory=&lt;function&gt;)&#39;</code>.</strong></li>
</ul>
<h3 id="Nonlocal"><a href="#Nonlocal" class="headerlink" title="Nonlocal"></a>Nonlocal</h3><p><strong>If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a ‘global’ or a ‘nonlocal’.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_counter</span><span class="params">()</span>:</span></span><br><span class="line">    i = <span class="number">0</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">out</span><span class="params">()</span>:</span></span><br><span class="line">        <span class="keyword">nonlocal</span> i</span><br><span class="line">        i += <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> i</span><br><span class="line">    <span class="keyword">return</span> out</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>counter = get_counter()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>counter(), counter(), counter()</span><br><span class="line">(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</span><br></pre></td></tr></table></figure>
<h2 id="Decorator"><a href="#Decorator" class="headerlink" title="Decorator"></a>Decorator</h2><p><strong>A decorator takes a function, adds some functionality and returns it.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@decorator_name</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">function_that_gets_passed_to_decorator</span><span class="params">()</span>:</span></span><br><span class="line">    ...</span><br></pre></td></tr></table></figure>
<h3 id="Debugger-Example"><a href="#Debugger-Example" class="headerlink" title="Debugger Example"></a>Debugger Example</h3><p><strong>Decorator that prints function’s name every time it gets called.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> wraps</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">debug</span><span class="params">(func)</span>:</span></span><br><span class="line"><span class="meta">    @wraps(func)</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">out</span><span class="params">(*args, **kwargs)</span>:</span></span><br><span class="line">        print(func.__name__)</span><br><span class="line">        <span class="keyword">return</span> func(*args, **kwargs)</span><br><span class="line">    <span class="keyword">return</span> out</span><br><span class="line"></span><br><span class="line"><span class="meta">@debug</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span><span class="params">(x, y)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> x + y</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Wraps is a helper decorator that copies the metadata of the passed function (func) to the function it is wrapping (out).</strong></li>
<li><strong>Without it <code>&#39;add.__name__&#39;</code> would return <code>&#39;out&#39;</code>.</strong></li>
</ul>
<h3 id="LRU-Cache"><a href="#LRU-Cache" class="headerlink" title="LRU Cache"></a>LRU Cache</h3><p><strong>Decorator that caches function’s return values. All function’s arguments must be hashable.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> lru_cache</span><br><span class="line"></span><br><span class="line"><span class="meta">@lru_cache(maxsize=None)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">fib</span><span class="params">(n)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> n <span class="keyword">if</span> n &lt; <span class="number">2</span> <span class="keyword">else</span> fib(n<span class="number">-2</span>) + fib(n<span class="number">-1</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>CPython interpreter limits recursion depth to 1000 by default. To increase it use <code>&#39;sys.setrecursionlimit(&lt;depth&gt;)&#39;</code>.</strong></li>
</ul>
<h3 id="Parametrized-Decorator"><a href="#Parametrized-Decorator" class="headerlink" title="Parametrized Decorator"></a>Parametrized Decorator</h3><p><strong>A decorator that accepts arguments and returns a normal decorator that accepts a function.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> wraps</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">debug</span><span class="params">(print_result=False)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">decorator</span><span class="params">(func)</span>:</span></span><br><span class="line"><span class="meta">        @wraps(func)</span></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">out</span><span class="params">(*args, **kwargs)</span>:</span></span><br><span class="line">            result = func(*args, **kwargs)</span><br><span class="line">            print(func.__name__, result <span class="keyword">if</span> print_result <span class="keyword">else</span> <span class="string">''</span>)</span><br><span class="line">            <span class="keyword">return</span> result</span><br><span class="line">        <span class="keyword">return</span> out</span><br><span class="line">    <span class="keyword">return</span> decorator</span><br><span class="line"></span><br><span class="line"><span class="meta">@debug(print_result=True)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span><span class="params">(x, y)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> x + y</span><br></pre></td></tr></table></figure></p>
<h2 id="Class"><a href="#Class" class="headerlink" title="Class"></a>Class</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> &lt;<span class="title">name</span>&gt;:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, a)</span>:</span></span><br><span class="line">        self.a = a</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__repr__</span><span class="params">(self)</span>:</span></span><br><span class="line">        class_name = self.__class__.__name__</span><br><span class="line">        <span class="keyword">return</span> <span class="string">f'<span class="subst">&#123;class_name&#125;</span>(<span class="subst">&#123;self.a!r&#125;</span>)'</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__str__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> str(self.a)</span><br><span class="line"></span><br><span class="line"><span class="meta">    @classmethod</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_class_name</span><span class="params">(cls)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> cls.__name__</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Return value of repr() should be unambiguous and of str() readable.</strong></li>
<li><strong>If only repr() is defined, it will also be used for str().</strong></li>
</ul>
<h4 id="Str-use-cases"><a href="#Str-use-cases" class="headerlink" title="Str() use cases:"></a>Str() use cases:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">print(&lt;el&gt;)</span><br><span class="line">print(<span class="string">f'<span class="subst">&#123;&lt;el&gt;&#125;</span>'</span>)</span><br><span class="line"><span class="keyword">raise</span> Exception(&lt;el&gt;)</span><br><span class="line">loguru.logger.debug(&lt;el&gt;)</span><br><span class="line">csv.writer(&lt;file&gt;).writerow([&lt;el&gt;])</span><br></pre></td></tr></table></figure>
<h4 id="Repr-use-cases"><a href="#Repr-use-cases" class="headerlink" title="Repr() use cases:"></a>Repr() use cases:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">print([&lt;el&gt;])</span><br><span class="line">print(<span class="string">f'<span class="subst">&#123;&lt;el&gt;!r&#125;</span>'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>&lt;el&gt;</span><br><span class="line">loguru.logger.exception()</span><br><span class="line">Z = dataclasses.make_dataclass(<span class="string">'Z'</span>, [<span class="string">'a'</span>]); print(Z(&lt;el&gt;))</span><br></pre></td></tr></table></figure>
<h3 id="Constructor-Overloading"><a href="#Constructor-Overloading" class="headerlink" title="Constructor Overloading"></a>Constructor Overloading</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> &lt;<span class="title">name</span>&gt;:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, a=None)</span>:</span></span><br><span class="line">        self.a = a</span><br></pre></td></tr></table></figure>
<h3 id="Inheritance"><a href="#Inheritance" class="headerlink" title="Inheritance"></a>Inheritance</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, name, age)</span>:</span></span><br><span class="line">        self.name = name</span><br><span class="line">        self.age  = age</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Employee</span><span class="params">(Person)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, name, age, staff_num)</span>:</span></span><br><span class="line">        super().__init__(name, age)</span><br><span class="line">        self.staff_num = staff_num</span><br></pre></td></tr></table></figure>
<h3 id="Multiple-Inheritance"><a href="#Multiple-Inheritance" class="headerlink" title="Multiple Inheritance"></a>Multiple Inheritance</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span>:</span> <span class="keyword">pass</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span>:</span> <span class="keyword">pass</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span><span class="params">(A, B)</span>:</span> <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<p><strong>MRO determines the order in which parent classes are traversed when searching for a method:</strong><br><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>C.mro()</span><br><span class="line">[&lt;class 'C'&gt;, &lt;class 'A'&gt;, &lt;class 'B'&gt;, &lt;class 'object'&gt;]</span><br></pre></td></tr></table></figure></p>
<h3 id="Property"><a href="#Property" class="headerlink" title="Property"></a>Property</h3><p><strong>Pythonic way of implementing getters and setters.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyClass</span>:</span></span><br><span class="line"><span class="meta">    @property</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">a</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self._a</span><br><span class="line"></span><br><span class="line"><span class="meta">    @a.setter</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">a</span><span class="params">(self, value)</span>:</span></span><br><span class="line">        self._a = value</span><br></pre></td></tr></table></figure></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>el = MyClass()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>el.a = <span class="number">123</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>el.a</span><br><span class="line"><span class="number">123</span></span><br></pre></td></tr></table></figure>
<h3 id="Dataclass"><a href="#Dataclass" class="headerlink" title="Dataclass"></a>Dataclass</h3><p><strong>Decorator that automatically generates init(), repr() and eq() special methods.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> dataclasses <span class="keyword">import</span> dataclass, field</span><br><span class="line"></span><br><span class="line"><span class="meta">@dataclass(order=False, frozen=False)</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> &lt;<span class="title">class_name</span>&gt;:</span></span><br><span class="line">    &lt;attr_name_1&gt;: &lt;type&gt;</span><br><span class="line">    &lt;attr_name_2&gt;: &lt;type&gt; = &lt;default_value&gt;</span><br><span class="line">    &lt;attr_name_3&gt;: list/dict/set = field(default_factory=list/dict/set)</span><br></pre></td></tr></table></figure></p>
<ul>
<li><strong>Objects can be made sortable with <code>&#39;order=True&#39;</code> and/or immutable and hashable with <code>&#39;frozen=True&#39;</code>.</strong></li>
<li><strong>Function field() is needed because <code>&#39;&lt;attr_name&gt;: list = []&#39;</code> would make a list that is shared among all instances.</strong></li>
<li><strong>Default_factory can be any <a href="#callable">callable</a>.</strong></li>
</ul>
<h4 id="Inline-1"><a href="#Inline-1" class="headerlink" title="Inline:"></a>Inline:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> dataclasses <span class="keyword">import</span> make_dataclass</span><br><span class="line">&lt;class&gt; = make_dataclass('&lt;class_name&gt;', &lt;coll_of_attribute_names&gt;)</span><br><span class="line">&lt;class&gt; = make_dataclass('&lt;class_name&gt;', &lt;coll_of_tuples&gt;)</span><br><span class="line">&lt;tuple&gt; = (<span class="string">'&lt;attr_name&gt;'</span>, &lt;type&gt; [, &lt;default_value&gt;])</span><br></pre></td></tr></table></figure>
<h3 id="Slots"><a href="#Slots" class="headerlink" title="Slots"></a>Slots</h3><p><strong>Mechanism that restricts objects to attributes listed in ‘slots’ and significantly reduces their memory footprint.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyClassWithSlots</span>:</span></span><br><span class="line">    __slots__ = [<span class="string">'a'</span>]</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.a = <span class="number">1</span></span><br></pre></td></tr></table></figure>
<h3 id="Copy"><a href="#Copy" class="headerlink" title="Copy"></a>Copy</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> copy <span class="keyword">import</span> copy, deepcopy</span><br><span class="line">&lt;object&gt; = copy(&lt;object&gt;)</span><br><span class="line">&lt;object&gt; = deepcopy(&lt;object&gt;)</span><br></pre></td></tr></table></figure>
<h2 id="Duck-Types"><a href="#Duck-Types" class="headerlink" title="Duck Types"></a>Duck Types</h2><p><strong>A duck type is an implicit type that prescribes a set of special methods. Any object that has those methods defined is considered a member of that duck type.</strong></p>
<h3 id="Comparable"><a href="#Comparable" class="headerlink" title="Comparable"></a>Comparable</h3><ul>
<li><strong>If eq() method is not overridden, it returns <code>&#39;id(self) == id(other)&#39;</code>, which is the same as <code>&#39;self is other&#39;</code>.</strong></li>
<li><strong>That means all objects compare not equal by default.</strong></li>
<li><strong>Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted.</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyComparable</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, a)</span>:</span></span><br><span class="line">        self.a = a</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__eq__</span><span class="params">(self, other)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> isinstance(other, type(self)):</span><br><span class="line">            <span class="keyword">return</span> self.a == other.a</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">NotImplemented</span></span><br></pre></td></tr></table></figure>
<h3 id="Hashable"><a href="#Hashable" class="headerlink" title="Hashable"></a>Hashable</h3><ul>
<li><strong>Hashable object needs both hash() and eq() methods and its hash value should never change.</strong></li>
<li><strong>Hashable objects that compare equal must have the same hash value, meaning default hash() that returns <code>&#39;id(self)&#39;</code> will not do.</strong></li>
<li><strong>That is why Python automatically makes classes unhashable if you only implement eq().</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyHashable</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, a)</span>:</span></span><br><span class="line">        self._a = copy.deepcopy(a)</span><br><span class="line"><span class="meta">    @property</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">a</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self._a</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__eq__</span><span class="params">(self, other)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> isinstance(other, type(self)):</span><br><span class="line">            <span class="keyword">return</span> self.a == other.a</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">NotImplemented</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__hash__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> hash(self.a)</span><br></pre></td></tr></table></figure>
<h3 id="Sortable"><a href="#Sortable" class="headerlink" title="Sortable"></a>Sortable</h3><ul>
<li><strong>With total_ordering decorator you only need to provide eq() and one of lt(), gt(), le() or ge() special methods.</strong><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> total_ordering</span><br><span class="line"></span><br><span class="line"><span class="meta">@total_ordering</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MySortable</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, a)</span>:</span></span><br><span class="line">        self.a = a</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__eq__</span><span class="params">(self, other)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> isinstance(other, type(self)):</span><br><span class="line">            <span class="keyword">return</span> self.a == other.a</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">NotImplemented</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__lt__</span><span class="params">(self, other)</span>:</span></span><br><span class="line">        <span class="keyword">if</span> isinstance(other, type(self)):</span><br><span class="line">            <span class="keyword">return</span> self.a &lt; other.a</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">NotImplemented</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="Iterator-1"><a href="#Iterator-1" class="headerlink" title="Iterator"></a>Iterator</h3><ul>
<li><strong>Any object that defines methods next() and iter() is an iterator.</strong></li>
<li><strong>Next() should return next item or raise StopIteration.</strong></li>
<li><strong>Iter() should return ‘self’.</strong><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Counter</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.i = <span class="number">0</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__next__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.i += <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> self.i</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__iter__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self</span><br></pre></td></tr></table></figure>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>counter = Counter()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>next(counter), next(counter), next(counter)</span><br><span class="line">(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</span><br></pre></td></tr></table></figure>
<h4 id="Python-has-many-different-iterator-objects"><a href="#Python-has-many-different-iterator-objects" class="headerlink" title="Python has many different iterator objects:"></a>Python has many different iterator objects:</h4><ul>
<li><strong>Iterators returned by the <a href="#iterator">iter()</a> function, such as list_iterator and set_iterator.</strong></li>
<li><strong>Objects returned by the <a href="#itertools">itertools</a> module, such as count, repeat and cycle.</strong></li>
<li><strong>Generators returned by the <a href="#generator">generator functions</a> and <a href="#comprehension">generator expressions</a>.</strong></li>
<li><strong>File objects returned by the <a href="#open">open()</a> function, etc.</strong></li>
</ul>
<h3 id="Callable"><a href="#Callable" class="headerlink" title="Callable"></a>Callable</h3><ul>
<li><strong>All functions and classes have a call() method, hence are callable.</strong></li>
<li><strong>When this cheatsheet uses <code>&#39;&lt;function&gt;&#39;</code> for an argument, it actually means <code>&#39;&lt;callable&gt;&#39;</code>.</strong><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Counter</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.i = <span class="number">0</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__call__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.i += <span class="number">1</span></span><br><span class="line">        <span class="keyword">return</span> self.i</span><br></pre></td></tr></table></figure>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>counter = Counter()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>counter(), counter(), counter()</span><br><span class="line">(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</span><br></pre></td></tr></table></figure>
<h3 id="Context-Manager"><a href="#Context-Manager" class="headerlink" title="Context Manager"></a>Context Manager</h3><ul>
<li><strong>Enter() should lock the resources and return an object.</strong></li>
<li><strong>Exit() should release the resources.</strong><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyOpen</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, filename)</span>:</span></span><br><span class="line">        self.filename = filename</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__enter__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.file = open(self.filename)</span><br><span class="line">        <span class="keyword">return</span> self.file</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__exit__</span><span class="params">(self, *args)</span>:</span></span><br><span class="line">        self.file.close()</span><br></pre></td></tr></table></figure>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">with</span> open(<span class="string">'test.txt'</span>, <span class="string">'w'</span>) <span class="keyword">as</span> file:</span><br><span class="line"><span class="meta">... </span>    file.write(<span class="string">'Hello World!'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">with</span> MyOpen(<span class="string">'test.txt'</span>) <span class="keyword">as</span> file:</span><br><span class="line"><span class="meta">... </span>    print(file.read())</span><br><span class="line">Hello World!</span><br></pre></td></tr></table></figure>
<h2 id="Iterable-Duck-Types"><a href="#Iterable-Duck-Types" class="headerlink" title="Iterable Duck Types"></a>Iterable Duck Types</h2><h3 id="Iterable"><a href="#Iterable" class="headerlink" title="Iterable"></a>Iterable</h3><ul>
<li><strong>Only required method is iter(). It should return an iterator of object’s items.</strong></li>
<li><strong>Contains() automatically works on any object that has iter() defined.</strong><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyIterable</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, a)</span>:</span></span><br><span class="line">        self.a = a</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__iter__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">for</span> el <span class="keyword">in</span> self.a:</span><br><span class="line">            <span class="keyword">yield</span> el</span><br></pre></td></tr></table></figure>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>z = MyIterable([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>])</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>iter(z)</span><br><span class="line">&lt;generator object MyIterable.__iter__&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="number">1</span> <span class="keyword">in</span> z</span><br><span class="line"><span class="literal">True</span></span><br></pre></td></tr></table></figure>
<h3 id="Collection"><a href="#Collection" class="headerlink" title="Collection"></a>Collection</h3><ul>
<li><strong>Only required methods are iter() and len().</strong></li>
<li><strong>This cheatsheet actually means <code>&#39;&lt;iterable&gt;&#39;</code> when it uses <code>&#39;&lt;collection&gt;&#39;</code>.</strong></li>
<li><strong>I chose not to use the name ‘iterable’ because it sounds scarier and more vague than ‘collection’.</strong><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyCollection</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, a)</span>:</span></span><br><span class="line">        self.a = a</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__iter__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> iter(self.a)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__contains__</span><span class="params">(self, el)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> el <span class="keyword">in</span> self.a</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__len__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> len(self.a)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="Sequence"><a href="#Sequence" class="headerlink" title="Sequence"></a>Sequence</h3><ul>
<li><strong>Only required methods are len() and getitem().</strong></li>
<li><strong>Getitem() should return an item at index or raise IndexError.</strong></li>
<li><strong>Iter() and contains() automatically work on any object that has getitem() defined.</strong></li>
<li><strong>Reversed() automatically works on any object that has getitem() and len() defined.</strong><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MySequence</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, a)</span>:</span></span><br><span class="line">        self.a = a</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__iter__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> iter(self.a)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__contains__</span><span class="params">(self, el)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> el <span class="keyword">in</span> self.a</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__len__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> len(self.a)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__getitem__</span><span class="params">(self, i)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self.a[i]</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__reversed__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> reversed(self.a)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="Collections-abc-Sequence"><a href="#Collections-abc-Sequence" class="headerlink" title="Collections.abc.Sequence"></a>Collections.abc.Sequence</h3><ul>
<li><strong>It’s a richer interface than the basic sequence.</strong></li>
<li><strong>Extending it generates iter(), contains(), reversed(), index(), and count().</strong></li>
<li><strong>Unlike <code>&#39;abc.Iterable&#39;</code> and <code>&#39;abc.Collection&#39;</code>, it is not a duck type. That is why <code>&#39;issubclass(MySequence, collections.abc.Sequence)&#39;</code> would return False even if MySequence had all the methods defined.</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyAbcSequence</span><span class="params">(collections.abc.Sequence)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, a)</span>:</span></span><br><span class="line">        self.a = a</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__len__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> len(self.a)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__getitem__</span><span class="params">(self, i)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self.a[i]</span><br></pre></td></tr></table></figure>
<h4 id="Table-of-required-and-automatically-available-special-methods"><a href="#Table-of-required-and-automatically-available-special-methods" class="headerlink" title="Table of required and automatically available special methods:"></a>Table of required and automatically available special methods:</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">+------------+------------+------------+------------+--------------+</span><br><span class="line">|            |  Iterable  | Collection |  Sequence  | abc.Sequence |</span><br><span class="line">+------------+------------+------------+------------+--------------+</span><br><span class="line">| iter()     |    REQ     |    REQ     |    yes     |     yes      |</span><br><span class="line">| contains() |    yes     |    yes     |    yes     |     yes      |</span><br><span class="line">| len()      |            |    REQ     |    REQ     |     REQ      |</span><br><span class="line">| getitem()  |            |            |    REQ     |     REQ      |</span><br><span class="line">| reversed() |            |            |    yes     |     yes      |</span><br><span class="line">| index()    |            |            |            |     yes      |</span><br><span class="line">| count()    |            |            |            |     yes      |</span><br><span class="line">+------------+------------+------------+------------+--------------+</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping.</strong></li>
<li><strong>Names of their required methods are stored in <code>&#39;&lt;abc&gt;.__abstractmethods__&#39;</code>.</strong></li>
</ul>
<h2 id="Enum"><a href="#Enum" class="headerlink" title="Enum"></a>Enum</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> enum <span class="keyword">import</span> Enum, auto</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> &lt;<span class="title">enum_name</span>&gt;<span class="params">(Enum)</span>:</span></span><br><span class="line">    &lt;member_name_1&gt; = &lt;value_1&gt;</span><br><span class="line">    &lt;member_name_2&gt; = &lt;value_2_a&gt;, &lt;value_2_b&gt;</span><br><span class="line">    &lt;member_name_3&gt; = auto()</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>If there are no numeric values before auto(), it returns 1.</strong></li>
<li><strong>Otherwise it returns an increment of the last numeric value.</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;member&gt; = &lt;enum&gt;.&lt;member_name&gt;                <span class="comment"># Returns a member.</span></span><br><span class="line">&lt;member&gt; = &lt;enum&gt;[<span class="string">'&lt;member_name&gt;'</span>]             <span class="comment"># Returns a member or raises KeyError.</span></span><br><span class="line">&lt;member&gt; = &lt;enum&gt;(&lt;value&gt;)                     <span class="comment"># Returns a member or raises ValueError.</span></span><br><span class="line">&lt;str&gt;    = &lt;member&gt;.name                       <span class="comment"># Returns member's name.</span></span><br><span class="line">&lt;obj&gt;    = &lt;member&gt;.value                      <span class="comment"># Returns member's value.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">list_of_members = list(&lt;enum&gt;)</span><br><span class="line">member_names    = [a.name <span class="keyword">for</span> a <span class="keyword">in</span> &lt;enum&gt;]</span><br><span class="line">member_values   = [a.value <span class="keyword">for</span> a <span class="keyword">in</span> &lt;enum&gt;]</span><br><span class="line">random_member   = random.choice(list(&lt;enum&gt;))</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_next_member</span><span class="params">(member)</span>:</span></span><br><span class="line">    members = list(member.__class__)</span><br><span class="line">    index   = (members.index(member) + <span class="number">1</span>) % len(members)</span><br><span class="line">    <span class="keyword">return</span> members[index]</span><br></pre></td></tr></table></figure>
<h3 id="Inline-2"><a href="#Inline-2" class="headerlink" title="Inline"></a>Inline</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Cutlery = Enum(<span class="string">'Cutlery'</span>, [<span class="string">'fork'</span>, <span class="string">'knife'</span>, <span class="string">'spoon'</span>])</span><br><span class="line">Cutlery = Enum(<span class="string">'Cutlery'</span>, <span class="string">'fork knife spoon'</span>)</span><br><span class="line">Cutlery = Enum(<span class="string">'Cutlery'</span>, &#123;<span class="string">'fork'</span>: <span class="number">1</span>, <span class="string">'knife'</span>: <span class="number">2</span>, <span class="string">'spoon'</span>: <span class="number">3</span>&#125;)</span><br></pre></td></tr></table></figure>
<h4 id="Functions-can-not-be-values-so-they-must-be-wrapped"><a href="#Functions-can-not-be-values-so-they-must-be-wrapped" class="headerlink" title="Functions can not be values, so they must be wrapped:"></a>Functions can not be values, so they must be wrapped:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> partial</span><br><span class="line">LogicOp = Enum(<span class="string">'LogicOp'</span>, &#123;<span class="string">'AND'</span>: partial(<span class="keyword">lambda</span> l, r: l <span class="keyword">and</span> r),</span><br><span class="line">                           <span class="string">'OR'</span> : partial(<span class="keyword">lambda</span> l, r: l <span class="keyword">or</span> r)&#125;)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Another solution in this particular case, is to use <code>&#39;and_&#39;</code> and <code>&#39;or_&#39;</code> functions from module <a href="#operator">operator</a>.</strong></li>
</ul>
<h2 id="Exceptions"><a href="#Exceptions" class="headerlink" title="Exceptions"></a>Exceptions</h2><h3 id="Basic-Example"><a href="#Basic-Example" class="headerlink" title="Basic Example"></a>Basic Example</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    &lt;code&gt;</span><br><span class="line"><span class="keyword">except</span> &lt;exception&gt;:</span><br><span class="line">    &lt;code&gt;</span><br></pre></td></tr></table></figure>
<h3 id="Complex-Example"><a href="#Complex-Example" class="headerlink" title="Complex Example"></a>Complex Example</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    &lt;code_1&gt;</span><br><span class="line"><span class="keyword">except</span> &lt;exception_a&gt;:</span><br><span class="line">    &lt;code_2_a&gt;</span><br><span class="line"><span class="keyword">except</span> &lt;exception_b&gt;:</span><br><span class="line">    &lt;code_2_b&gt;</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    &lt;code_2_c&gt;</span><br><span class="line"><span class="keyword">finally</span>:</span><br><span class="line">    &lt;code_3&gt;</span><br></pre></td></tr></table></figure>
<h3 id="Catching-Exceptions"><a href="#Catching-Exceptions" class="headerlink" title="Catching Exceptions"></a>Catching Exceptions</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">except</span> &lt;exception&gt;:</span><br><span class="line"><span class="keyword">except</span> &lt;exception&gt; <span class="keyword">as</span> &lt;name&gt;:</span><br><span class="line"><span class="keyword">except</span> (&lt;exception&gt;, ...):</span><br><span class="line"><span class="keyword">except</span> (&lt;exception&gt;, ...) <span class="keyword">as</span> &lt;name&gt;:</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Also catches subclasses of the exception.</strong></li>
</ul>
<h3 id="Raising-Exceptions"><a href="#Raising-Exceptions" class="headerlink" title="Raising Exceptions"></a>Raising Exceptions</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">raise</span> &lt;exception&gt;</span><br><span class="line"><span class="keyword">raise</span> &lt;exception&gt;()</span><br><span class="line"><span class="keyword">raise</span> &lt;exception&gt;(&lt;el&gt;)</span><br><span class="line"><span class="keyword">raise</span> &lt;exception&gt;(&lt;el&gt;, ...)</span><br></pre></td></tr></table></figure>
<h4 id="Re-raising-caught-exception"><a href="#Re-raising-caught-exception" class="headerlink" title="Re-raising caught exception:"></a>Re-raising caught exception:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">except</span> &lt;exception&gt;:</span><br><span class="line">    &lt;code&gt;</span><br><span class="line">    <span class="keyword">raise</span></span><br></pre></td></tr></table></figure>
<h4 id="Useful-built-in-exceptions"><a href="#Useful-built-in-exceptions" class="headerlink" title="Useful built-in exceptions:"></a>Useful built-in exceptions:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">raise</span> ValueError(<span class="string">'Argument is of right type but inappropriate value!'</span>)</span><br><span class="line"><span class="keyword">raise</span> TypeError(<span class="string">'Argument is of wrong type!'</span>)</span><br><span class="line"><span class="keyword">raise</span> RuntimeError(<span class="string">'None of above!'</span>)</span><br></pre></td></tr></table></figure>
<h3 id="Common-Built-in-Exceptions"><a href="#Common-Built-in-Exceptions" class="headerlink" title="Common Built-in Exceptions"></a>Common Built-in Exceptions</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">BaseException</span><br><span class="line"> +-- SystemExit                   # Raised by the sys.exit() function.</span><br><span class="line"> +-- KeyboardInterrupt            # Raised when the user hits the interrupt key (ctrl-c).</span><br><span class="line"> +-- Exception                    # User-defined exceptions should be derived from this class.</span><br><span class="line">      +-- StopIteration           # Raised by next() when run on an empty iterator.</span><br><span class="line">      +-- ArithmeticError         # Base class for arithmetic errors.</span><br><span class="line">      |    +-- ZeroDivisionError  # Raised when dividing by zero.</span><br><span class="line">      +-- AttributeError          # Raised when an attribute is missing.</span><br><span class="line">      +-- EOFError                # Raised by input() when it hits end-of-file condition.</span><br><span class="line">      +-- LookupError             # Raised when a look-up on a sequence or dict fails.</span><br><span class="line">      |    +-- IndexError         # Raised when a sequence index is out of range.</span><br><span class="line">      |    +-- KeyError           # Raised when a dictionary key is not found.</span><br><span class="line">      +-- NameError               # Raised when a variable name is not found.</span><br><span class="line">      +-- OSError                 # Failures such as “file not found” or “disk full”.</span><br><span class="line">      |    +-- FileNotFoundError  # When a file or directory is requested but doesn&apos;t exist.</span><br><span class="line">      +-- RuntimeError            # Raised by errors that don&apos;t fall in other categories.</span><br><span class="line">      |    +-- RecursionError     # Raised when the the maximum recursion depth is exceeded.</span><br><span class="line">      +-- TypeError               # Raised when an argument is of wrong type.</span><br><span class="line">      +-- ValueError              # When an argument is of right type but inappropriate value.</span><br><span class="line">           +-- UnicodeError       # Raised when encoding/decoding strings from/to bytes fails.</span><br></pre></td></tr></table></figure>
<h4 id="Collections-and-their-exceptions"><a href="#Collections-and-their-exceptions" class="headerlink" title="Collections and their exceptions:"></a>Collections and their exceptions:</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">+-----------+------------+------------+------------+</span><br><span class="line">|           |    list    |    dict    |    set     |</span><br><span class="line">+-----------+------------+------------+------------+</span><br><span class="line">| getitem() | IndexError |  KeyError  |            |</span><br><span class="line">| pop()     | IndexError |  KeyError  |  KeyError  |</span><br><span class="line">| remove()  | ValueError |            |  KeyError  |</span><br><span class="line">| index()   | ValueError |            |            |</span><br><span class="line">+-----------+------------+------------+------------+</span><br></pre></td></tr></table></figure>
<h3 id="User-defined-Exceptions"><a href="#User-defined-Exceptions" class="headerlink" title="User-defined Exceptions"></a>User-defined Exceptions</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyError</span><span class="params">(Exception)</span>:</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyInputError</span><span class="params">(MyError)</span>:</span></span><br><span class="line">    <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>
<h2 id="Print"><a href="#Print" class="headerlink" title="Print"></a>Print</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(&lt;el_1&gt;, ..., sep=<span class="string">' '</span>, end=<span class="string">'\n'</span>, file=sys.stdout, flush=<span class="literal">False</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Use <code>&#39;file=sys.stderr&#39;</code> for errors.</strong></li>
<li><strong>Use <code>&#39;flush=True&#39;</code> to forcibly flush the stream.</strong></li>
</ul>
<h3 id="Pretty-Print"><a href="#Pretty-Print" class="headerlink" title="Pretty Print"></a>Pretty Print</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> pprint <span class="keyword">import</span> pprint</span><br><span class="line">pprint(&lt;collection&gt;, width=<span class="number">80</span>, depth=<span class="literal">None</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Levels deeper than ‘depth’ get replaced by ‘…’.</strong></li>
</ul>
<h2 id="Input"><a href="#Input" class="headerlink" title="Input"></a>Input</h2><p><strong>Reads a line from user input or pipe if present.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;str&gt; = input(prompt=<span class="literal">None</span>)</span><br></pre></td></tr></table></figure></p>
<ul>
<li><strong>Trailing newline gets stripped.</strong></li>
<li><strong>Prompt string is printed to the standard output before reading input.</strong></li>
<li><strong>Raises EOFError when user hits EOF or input stream gets exhausted.</strong></li>
</ul>
<h2 id="Command-Line-Arguments"><a href="#Command-Line-Arguments" class="headerlink" title="Command Line Arguments"></a>Command Line Arguments</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> sys</span><br><span class="line">script_name = sys.argv[<span class="number">0</span>]</span><br><span class="line">arguments   = sys.argv[<span class="number">1</span>:]</span><br></pre></td></tr></table></figure>
<h3 id="Argparse"><a href="#Argparse" class="headerlink" title="Argparse"></a>Argparse</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> argparse <span class="keyword">import</span> ArgumentParser, FileType</span><br><span class="line">p = ArgumentParser(description=&lt;str&gt;)</span><br><span class="line">p.add_argument(<span class="string">'-&lt;short_name&gt;'</span>, <span class="string">'--&lt;name&gt;'</span>, action=<span class="string">'store_true'</span>)  <span class="comment"># Flag</span></span><br><span class="line">p.add_argument(<span class="string">'-&lt;short_name&gt;'</span>, <span class="string">'--&lt;name&gt;'</span>, type=&lt;type&gt;)          <span class="comment"># Option</span></span><br><span class="line">p.add_argument(<span class="string">'&lt;name&gt;'</span>, type=&lt;type&gt;, nargs=<span class="number">1</span>)                    <span class="comment"># First argument</span></span><br><span class="line">p.add_argument(<span class="string">'&lt;name&gt;'</span>, type=&lt;type&gt;, nargs=<span class="string">'+'</span>)                  <span class="comment"># Remaining arguments</span></span><br><span class="line">p.add_argument(<span class="string">'&lt;name&gt;'</span>, type=&lt;type&gt;, nargs=<span class="string">'*'</span>)                  <span class="comment"># Optional arguments</span></span><br><span class="line">args  = p.parse_args()                                            <span class="comment"># Exits on error.</span></span><br><span class="line">value = args.&lt;name&gt;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Use <code>&#39;help=&lt;str&gt;&#39;</code> to set argument description.</strong></li>
<li><strong>Use <code>&#39;default=&lt;el&gt;&#39;</code> to set the default value.</strong></li>
<li><strong>Use <code>&#39;type=FileType(&lt;mode&gt;)&#39;</code> for files.</strong></li>
</ul>
<h2 id="Open"><a href="#Open" class="headerlink" title="Open"></a>Open</h2><p><strong>Opens the file and returns a corresponding file object.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;file&gt; = open(<span class="string">'&lt;path&gt;'</span>, mode=<span class="string">'r'</span>, encoding=<span class="literal">None</span>, newline=<span class="literal">None</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong><code>&#39;encoding=None&#39;</code> means that the default encoding is used, which is platform dependent. Best practice is to use <code>&#39;encoding=&quot;utf-8&quot;&#39;</code> whenever possible.</strong></li>
<li><strong><code>&#39;newline=None&#39;</code> means all different end of line combinations are converted to ‘\n’ on read, while on write all ‘\n’ characters are converted to system’s default line separator.</strong></li>
<li><strong><code>&#39;newline=&quot;&quot;&#39;</code> means no conversions take place, but input is still broken into chunks by readline() and readlines() on either ‘\n’, ‘\r’ or ‘\r\n’.</strong></li>
</ul>
<h3 id="Modes"><a href="#Modes" class="headerlink" title="Modes"></a>Modes</h3><ul>
<li><strong><code>&#39;r&#39;</code>  - Read (default).</strong></li>
<li><strong><code>&#39;w&#39;</code>  - Write (truncate).</strong></li>
<li><strong><code>&#39;x&#39;</code>  - Write or fail if the file already exists.</strong></li>
<li><strong><code>&#39;a&#39;</code>  - Append.</strong></li>
<li><strong><code>&#39;w+&#39;</code> - Read and write (truncate).</strong></li>
<li><strong><code>&#39;r+&#39;</code> - Read and write from the start.</strong></li>
<li><strong><code>&#39;a+&#39;</code> - Read and write from the end.</strong></li>
<li><strong><code>&#39;t&#39;</code>  - Text mode (default).</strong></li>
<li><strong><code>&#39;b&#39;</code>  - Binary mode.</strong></li>
</ul>
<h3 id="Exceptions-1"><a href="#Exceptions-1" class="headerlink" title="Exceptions"></a>Exceptions</h3><ul>
<li><strong><code>&#39;FileNotFoundError&#39;</code> can be risen when reading with <code>&#39;r&#39;</code> or <code>&#39;r+&#39;</code>.</strong></li>
<li><strong><code>&#39;FileExistsError&#39;</code> can be risen when writing with <code>&#39;x&#39;</code>.</strong></li>
<li><strong><code>&#39;IsADirectoryError&#39;</code> and <code>&#39;PermissionError&#39;</code> can be risen by any.</strong></li>
<li><strong><code>&#39;OSError&#39;</code> is the parent class of all listed exceptions.</strong></li>
</ul>
<h3 id="File-Object"><a href="#File-Object" class="headerlink" title="File Object"></a>File Object</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;file&gt;.seek(<span class="number">0</span>)                      <span class="comment"># Moves to the start of the file.</span></span><br><span class="line">&lt;file&gt;.seek(offset)                 <span class="comment"># Moves 'offset' chars/bytes from the start.</span></span><br><span class="line">&lt;file&gt;.seek(<span class="number">0</span>, <span class="number">2</span>)                   <span class="comment"># Moves to the end of the file.</span></span><br><span class="line">&lt;bin_file&gt;.seek(±offset, &lt;anchor&gt;)  <span class="comment"># Anchor: 0 start, 1 current pos., 2 end.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;str/bytes&gt; = &lt;file&gt;.read(size=<span class="number">-1</span>)  <span class="comment"># Reads 'size' chars/bytes or until EOF.</span></span><br><span class="line">&lt;str/bytes&gt; = &lt;file&gt;.readline()     <span class="comment"># Returns a line or empty string on EOF.</span></span><br><span class="line">&lt;list&gt;      = &lt;file&gt;.readlines()    <span class="comment"># Returns a list of remaining lines.</span></span><br><span class="line">&lt;str/bytes&gt; = next(&lt;file&gt;)          <span class="comment"># Returns a line using buffer. Do not mix.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;file&gt;.write(&lt;str/bytes&gt;)           <span class="comment"># Writes a string or bytes object.</span></span><br><span class="line">&lt;file&gt;.writelines(&lt;collection&gt;)     <span class="comment"># Writes a coll. of strings or bytes objects.</span></span><br><span class="line">&lt;file&gt;.flush()                      <span class="comment"># Flushes write buffer.</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Methods do not add or strip trailing newlines, even writelines().</strong></li>
</ul>
<h3 id="Read-Text-from-File"><a href="#Read-Text-from-File" class="headerlink" title="Read Text from File"></a>Read Text from File</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">read_file</span><span class="params">(filename)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> open(filename, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">        <span class="keyword">return</span> file.readlines()</span><br></pre></td></tr></table></figure>
<h3 id="Write-Text-to-File"><a href="#Write-Text-to-File" class="headerlink" title="Write Text to File"></a>Write Text to File</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">write_to_file</span><span class="params">(filename, text)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> open(filename, <span class="string">'w'</span>, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">        file.write(text)</span><br></pre></td></tr></table></figure>
<h2 id="Path"><a href="#Path" class="headerlink" title="Path"></a>Path</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> os <span class="keyword">import</span> getcwd, path, listdir, scandir</span><br><span class="line"><span class="keyword">from</span> glob <span class="keyword">import</span> glob</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;str&gt;  = getcwd()                   <span class="comment"># Returns the current working directory.</span></span><br><span class="line">&lt;str&gt;  = path.join(&lt;path&gt;, ...)     <span class="comment"># Joins two or more pathname components.</span></span><br><span class="line">&lt;str&gt;  = path.abspath(&lt;path&gt;)       <span class="comment"># Return an absolute path.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;str&gt;  = path.basename(&lt;path&gt;)      <span class="comment"># Returns final component.</span></span><br><span class="line">&lt;str&gt;  = path.dirname(&lt;path&gt;)       <span class="comment"># Returns path without final component.</span></span><br><span class="line">&lt;tup.&gt; = path.splitext(&lt;path&gt;)      <span class="comment"># Splits on last period of final component.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;list&gt; = listdir(path=<span class="string">'.'</span>)          <span class="comment"># Returns filenames located at path.</span></span><br><span class="line">&lt;list&gt; = glob(<span class="string">'&lt;pattern&gt;'</span>)          <span class="comment"># Returns paths matching the wildcard pattern.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;bool&gt; = path.exists(&lt;path&gt;)        <span class="comment"># Or: &lt;Path&gt;.exists()</span></span><br><span class="line">&lt;bool&gt; = path.isfile(&lt;path&gt;)        <span class="comment"># Or: &lt;DirEntry/Path&gt;.is_file()</span></span><br><span class="line">&lt;bool&gt; = path.isdir(&lt;path&gt;)         <span class="comment"># Or: &lt;DirEntry/Path&gt;.is_dir()</span></span><br></pre></td></tr></table></figure>
<h3 id="DirEntry"><a href="#DirEntry" class="headerlink" title="DirEntry"></a>DirEntry</h3><p><strong>Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type information.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;iter&gt; = scandir(path=<span class="string">'.'</span>)          <span class="comment"># Returns DirEntry objects located at path.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;str&gt;  = &lt;DirEntry&gt;.path            <span class="comment"># Returns path as a string.</span></span><br><span class="line">&lt;str&gt;  = &lt;DirEntry&gt;.name            <span class="comment"># Returns final component as a string.</span></span><br><span class="line">&lt;file&gt; = open(&lt;DirEntry&gt;)           <span class="comment"># Opens the file and returns a file object.</span></span><br></pre></td></tr></table></figure>
<h3 id="Path-Object"><a href="#Path-Object" class="headerlink" title="Path Object"></a>Path Object</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> pathlib <span class="keyword">import</span> Path</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;Path&gt; = Path(&lt;path&gt; [, ...])       <span class="comment"># Accepts strings, Paths and DirEntry objects.</span></span><br><span class="line">&lt;Path&gt; = &lt;path&gt; / &lt;path&gt; [/ ...]    <span class="comment"># One of the paths must be a Path object.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;Path&gt; = Path()                     <span class="comment"># Returns relative cwd. Also Path('.').</span></span><br><span class="line">&lt;Path&gt; = Path.cwd()                 <span class="comment"># Returns absolute cwd. Also Path().resolve().</span></span><br><span class="line">&lt;Path&gt; = &lt;Path&gt;.resolve()           <span class="comment"># Returns absolute Path without symlinks.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;Path&gt; = &lt;Path&gt;.parent              <span class="comment"># Returns Path without final component.</span></span><br><span class="line">&lt;str&gt;  = &lt;Path&gt;.name                <span class="comment"># Returns final component as a string.</span></span><br><span class="line">&lt;str&gt;  = &lt;Path&gt;.stem                <span class="comment"># Returns final component without extension.</span></span><br><span class="line">&lt;str&gt;  = &lt;Path&gt;.suffix              <span class="comment"># Returns final component's extension.</span></span><br><span class="line">&lt;tup.&gt; = &lt;Path&gt;.parts               <span class="comment"># Returns all components as strings.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;iter&gt; = &lt;Path&gt;.iterdir()           <span class="comment"># Returns dir contents as Path objects.</span></span><br><span class="line">&lt;iter&gt; = &lt;Path&gt;.glob(<span class="string">'&lt;pattern&gt;'</span>)   <span class="comment"># Returns Paths matching the wildcard pattern.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;str&gt;  = str(&lt;Path&gt;)                <span class="comment"># Returns path as a string.</span></span><br><span class="line">&lt;file&gt; = open(&lt;Path&gt;)               <span class="comment"># Opens the file and returns a file object.</span></span><br></pre></td></tr></table></figure>
<h2 id="OS-Commands"><a href="#OS-Commands" class="headerlink" title="OS Commands"></a>OS Commands</h2><h3 id="Files-and-Directories"><a href="#Files-and-Directories" class="headerlink" title="Files and Directories"></a>Files and Directories</h3><ul>
<li><strong>Paths can be either strings, Paths, or DirEntry objects.</strong></li>
<li><strong>Functions report OS related errors by raising either OSError or one of its <a href="#exceptions-1">subclasses</a>.</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> os, shutil</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">os.chdir(&lt;path&gt;)                    <span class="comment"># Changes current working directory.</span></span><br><span class="line">os.mkdir(&lt;path&gt;, mode=<span class="number">0o777</span>)        <span class="comment"># Creates a directory. Mode is in octal.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">shutil.copy(<span class="keyword">from</span>, to)               <span class="comment"># Copies the file.</span></span><br><span class="line">shutil.copytree(<span class="keyword">from</span>, to)           <span class="comment"># Copies the directory.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">os.rename(<span class="keyword">from</span>, to)                 <span class="comment"># Renames the file or directory.</span></span><br><span class="line">os.replace(<span class="keyword">from</span>, to)                <span class="comment"># Same, but overwrites 'to' if it exists.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">os.remove(&lt;path&gt;)                   <span class="comment"># Deletes the file.</span></span><br><span class="line">os.rmdir(&lt;path&gt;)                    <span class="comment"># Deletes empty directory.</span></span><br><span class="line">shutil.rmtree(&lt;path&gt;)               <span class="comment"># Deletes non-empty directory.</span></span><br></pre></td></tr></table></figure>
<h3 id="Shell-Commands"><a href="#Shell-Commands" class="headerlink" title="Shell Commands"></a>Shell Commands</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> os</span><br><span class="line">&lt;str&gt; = os.popen(<span class="string">'&lt;shell_command&gt;'</span>).read()</span><br></pre></td></tr></table></figure>
<h4 id="Using-subprocess"><a href="#Using-subprocess" class="headerlink" title="Using subprocess:"></a>Using subprocess:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> subprocess, shlex</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = subprocess.run(shlex.split(<span class="string">'ls -a'</span>), stdout=subprocess.PIPE)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.stdout</span><br><span class="line"><span class="string">b'.\n..\nfile1.txt\nfile2.txt\n'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.returncode</span><br><span class="line"><span class="number">0</span></span><br></pre></td></tr></table></figure>
<h2 id="JSON"><a href="#JSON" class="headerlink" title="JSON"></a>JSON</h2><p><strong>Text file format for storing collections of strings and numbers.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> json</span><br><span class="line">&lt;str&gt;    = json.dumps(&lt;object&gt;, ensure_ascii=<span class="literal">True</span>, indent=<span class="literal">None</span>)</span><br><span class="line">&lt;object&gt; = json.loads(&lt;str&gt;)</span><br></pre></td></tr></table></figure>
<h3 id="Read-Object-from-JSON-File"><a href="#Read-Object-from-JSON-File" class="headerlink" title="Read Object from JSON File"></a>Read Object from JSON File</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">read_json_file</span><span class="params">(filename)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> open(filename, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">        <span class="keyword">return</span> json.load(file)</span><br></pre></td></tr></table></figure>
<h3 id="Write-Object-to-JSON-File"><a href="#Write-Object-to-JSON-File" class="headerlink" title="Write Object to JSON File"></a>Write Object to JSON File</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">write_to_json_file</span><span class="params">(filename, an_object)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> open(filename, <span class="string">'w'</span>, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">        json.dump(an_object, file, ensure_ascii=<span class="literal">False</span>, indent=<span class="number">2</span>)</span><br></pre></td></tr></table></figure>
<h2 id="Pickle"><a href="#Pickle" class="headerlink" title="Pickle"></a>Pickle</h2><p><strong>Binary file format for storing objects.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pickle</span><br><span class="line">&lt;bytes&gt;  = pickle.dumps(&lt;object&gt;)</span><br><span class="line">&lt;object&gt; = pickle.loads(&lt;bytes&gt;)</span><br></pre></td></tr></table></figure>
<h3 id="Read-Object-from-File"><a href="#Read-Object-from-File" class="headerlink" title="Read Object from File"></a>Read Object from File</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">read_pickle_file</span><span class="params">(filename)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> open(filename, <span class="string">'rb'</span>) <span class="keyword">as</span> file:</span><br><span class="line">        <span class="keyword">return</span> pickle.load(file)</span><br></pre></td></tr></table></figure>
<h3 id="Write-Object-to-File"><a href="#Write-Object-to-File" class="headerlink" title="Write Object to File"></a>Write Object to File</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">write_to_pickle_file</span><span class="params">(filename, an_object)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> open(filename, <span class="string">'wb'</span>) <span class="keyword">as</span> file:</span><br><span class="line">        pickle.dump(an_object, file)</span><br></pre></td></tr></table></figure>
<h2 id="CSV"><a href="#CSV" class="headerlink" title="CSV"></a>CSV</h2><p><strong>Text file format for storing spreadsheets.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> csv</span><br></pre></td></tr></table></figure>
<h3 id="Read"><a href="#Read" class="headerlink" title="Read"></a>Read</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;reader&gt; = csv.reader(&lt;file&gt;, dialect=<span class="string">'excel'</span>, delimiter=<span class="string">','</span>)</span><br><span class="line">&lt;list&gt;   = next(&lt;reader&gt;)           <span class="comment"># Returns next row as a list of strings.</span></span><br><span class="line">&lt;list&gt;   = list(&lt;reader&gt;)           <span class="comment"># Returns list of remaining rows.</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>File must be opened with <code>&#39;newline=&quot;&quot;&#39;</code> argument, or newlines embedded inside quoted fields will not be interpreted correctly!</strong></li>
</ul>
<h3 id="Write"><a href="#Write" class="headerlink" title="Write"></a>Write</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;writer&gt; = csv.writer(&lt;file&gt;, dialect=<span class="string">'excel'</span>, delimiter=<span class="string">','</span>)</span><br><span class="line">&lt;writer&gt;.writerow(&lt;collection&gt;)     <span class="comment"># Encodes objects using `str(&lt;el&gt;)`.</span></span><br><span class="line">&lt;writer&gt;.writerows(&lt;coll_of_coll&gt;)  <span class="comment"># Appends multiple rows.</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>File must be opened with <code>&#39;newline=&quot;&quot;&#39;</code> argument, or an extra ‘\r’ will be added on platforms that use ‘\r\n’ linendings!</strong></li>
</ul>
<h3 id="Parameters"><a href="#Parameters" class="headerlink" title="Parameters"></a>Parameters</h3><ul>
<li><strong><code>&#39;dialect&#39;</code> - Master parameter that sets the default values.</strong></li>
<li><strong><code>&#39;delimiter&#39;</code> - A one-character string used to separate fields.</strong></li>
<li><strong><code>&#39;quotechar&#39;</code> - Character for quoting fields that contain special characters.</strong></li>
<li><strong><code>&#39;doublequote&#39;</code> - Whether quotechars inside fields get doubled or escaped.</strong></li>
<li><strong><code>&#39;skipinitialspace&#39;</code> - Whether whitespace after delimiter gets stripped.</strong></li>
<li><strong><code>&#39;lineterminator&#39;</code> - How does writer terminate lines.</strong></li>
<li><strong><code>&#39;quoting&#39;</code> - Controls the amount of quoting: 0 - as necessary, 1 - all.</strong></li>
<li><strong><code>&#39;escapechar&#39;</code> - Character for escaping ‘quotechar’ if ‘doublequote’ is false.</strong></li>
</ul>
<h3 id="Dialects"><a href="#Dialects" class="headerlink" title="Dialects"></a>Dialects</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">+------------------+--------------+--------------+--------------+</span><br><span class="line">|                  |     excel    |   excel-tab  |     unix     |</span><br><span class="line">+------------------+--------------+--------------+--------------+</span><br><span class="line">| delimiter        |       &apos;,&apos;    |      &apos;\t&apos;    |       &apos;,&apos;    |</span><br><span class="line">| quotechar        |       &apos;&quot;&apos;    |       &apos;&quot;&apos;    |       &apos;&quot;&apos;    |</span><br><span class="line">| doublequote      |      True    |      True    |      True    |</span><br><span class="line">| skipinitialspace |     False    |     False    |     False    |</span><br><span class="line">| lineterminator   |    &apos;\r\n&apos;    |    &apos;\r\n&apos;    |      &apos;\n&apos;    |</span><br><span class="line">| quoting          |         0    |         0    |         1    |</span><br><span class="line">| escapechar       |      None    |      None    |      None    |</span><br><span class="line">+------------------+--------------+--------------+--------------+</span><br></pre></td></tr></table></figure>
<h3 id="Read-Rows-from-CSV-File"><a href="#Read-Rows-from-CSV-File" class="headerlink" title="Read Rows from CSV File"></a>Read Rows from CSV File</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">read_csv_file</span><span class="params">(filename)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> open(filename, encoding=<span class="string">'utf-8'</span>, newline=<span class="string">''</span>) <span class="keyword">as</span> file:</span><br><span class="line">        <span class="keyword">return</span> list(csv.reader(file))</span><br></pre></td></tr></table></figure>
<h3 id="Write-Rows-to-CSV-File"><a href="#Write-Rows-to-CSV-File" class="headerlink" title="Write Rows to CSV File"></a>Write Rows to CSV File</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">write_to_csv_file</span><span class="params">(filename, rows)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> open(filename, <span class="string">'w'</span>, encoding=<span class="string">'utf-8'</span>, newline=<span class="string">''</span>) <span class="keyword">as</span> file:</span><br><span class="line">        writer = csv.writer(file)</span><br><span class="line">        writer.writerows(rows)</span><br></pre></td></tr></table></figure>
<h2 id="SQLite"><a href="#SQLite" class="headerlink" title="SQLite"></a>SQLite</h2><p><strong>Server-less database engine that stores each database into separate file.</strong></p>
<h3 id="Connect"><a href="#Connect" class="headerlink" title="Connect"></a>Connect</h3><p><strong>Opens a connection to the database file. Creates a new file if path doesn’t exist.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> sqlite3</span><br><span class="line">db = sqlite3.connect(<span class="string">'&lt;path&gt;'</span>)                  <span class="comment"># Also ':memory:'.</span></span><br><span class="line">...</span><br><span class="line">db.close()</span><br></pre></td></tr></table></figure></p>
<h3 id="Read-1"><a href="#Read-1" class="headerlink" title="Read"></a>Read</h3><p><strong>Returned values can be of type str, int, float, bytes or None.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;cursor&gt; = db.execute(<span class="string">'&lt;query&gt;'</span>)                <span class="comment"># Can raise sqlite3.OperationalError.</span></span><br><span class="line">&lt;tuple&gt;  = &lt;cursor&gt;.fetchone()                  <span class="comment"># Returns next row. Also next(&lt;cursor&gt;).</span></span><br><span class="line">&lt;list&gt;   = &lt;cursor&gt;.fetchall()                  <span class="comment"># Returns remaining rows.</span></span><br></pre></td></tr></table></figure></p>
<h3 id="Write-1"><a href="#Write-1" class="headerlink" title="Write"></a>Write</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.execute(<span class="string">'&lt;query&gt;'</span>)</span><br><span class="line">db.commit()</span><br></pre></td></tr></table></figure>
<h4 id="Or"><a href="#Or" class="headerlink" title="Or:"></a>Or:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> db:</span><br><span class="line">    db.execute(<span class="string">'&lt;query&gt;'</span>)</span><br></pre></td></tr></table></figure>
<h3 id="Placeholders"><a href="#Placeholders" class="headerlink" title="Placeholders"></a>Placeholders</h3><ul>
<li><strong>Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.</strong></li>
<li><strong>Bools will be stored and returned as ints and dates as <a href="#encode">ISO formatted strings</a>.</strong><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.execute(<span class="string">'&lt;query&gt;'</span>, &lt;list/tuple&gt;)             <span class="comment"># Replaces '?'s in query with values.</span></span><br><span class="line">db.execute(<span class="string">'&lt;query&gt;'</span>, &lt;dict/namedtuple&gt;)        <span class="comment"># Replaces ':&lt;key&gt;'s with values.</span></span><br><span class="line">db.executemany(<span class="string">'&lt;query&gt;'</span>, &lt;coll_of_above&gt;)      <span class="comment"># Runs execute() many times.</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="Example"><a href="#Example" class="headerlink" title="Example"></a>Example</h3><p><strong>In this example values are not actually saved because <code>&#39;db.commit()&#39;</code> is omitted!</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>db = sqlite3.connect(<span class="string">'test.db'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>db.execute(<span class="string">'create table t (a, b, c)'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>db.execute(<span class="string">'insert into t values (1, 2, 3)'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>db.execute(<span class="string">'select * from t'</span>).fetchall()</span><br><span class="line">[(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)]</span><br><span class="line">``` </span><br><span class="line"></span><br><span class="line"><span class="comment">### MySQL</span></span><br><span class="line">**Has a very similar interface, <span class="keyword">with</span> differences listed below.**</span><br><span class="line">```python</span><br><span class="line"><span class="comment"># $ pip3 install mysql-connector</span></span><br><span class="line"><span class="keyword">from</span> mysql <span class="keyword">import</span> connector</span><br><span class="line">db = connector.connect(host=&lt;str&gt;, user=&lt;str&gt;, password=&lt;str&gt;, database=&lt;str&gt;)</span><br><span class="line">&lt;cursor&gt; = db.cursor()</span><br><span class="line">&lt;cursor&gt;.execute(<span class="string">'&lt;query&gt;'</span>)                     <span class="comment"># Only cursor has execute method.</span></span><br><span class="line">&lt;cursor&gt;.execute(<span class="string">'&lt;query&gt;'</span>, &lt;list/tuple&gt;)       <span class="comment"># Replaces '%s's in query with values.</span></span><br><span class="line">&lt;cursor&gt;.execute(<span class="string">'&lt;query&gt;'</span>, &lt;dict/namedtuple&gt;)  <span class="comment"># Replaces '%(&lt;key&gt;)s's with values.</span></span><br></pre></td></tr></table></figure></p>
<h2 id="Bytes"><a href="#Bytes" class="headerlink" title="Bytes"></a>Bytes</h2><p><strong>Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bytes&gt; = <span class="string">b'&lt;str&gt;'</span>                       <span class="comment"># Only accepts ASCII characters and \x00 - \xff.</span></span><br><span class="line">&lt;int&gt;   = &lt;bytes&gt;[&lt;index&gt;]               <span class="comment"># Returns int in range from 0 to 255.</span></span><br><span class="line">&lt;bytes&gt; = &lt;bytes&gt;[&lt;slice&gt;]               <span class="comment"># Returns bytes even if it has only one element.</span></span><br><span class="line">&lt;bytes&gt; = &lt;bytes&gt;.join(&lt;coll_of_bytes&gt;)  <span class="comment"># Joins elements using bytes object as separator.</span></span><br></pre></td></tr></table></figure>
<h3 id="Encode-1"><a href="#Encode-1" class="headerlink" title="Encode"></a>Encode</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;bytes&gt; = bytes(&lt;coll_of_ints&gt;)          <span class="comment"># Ints must be in range from 0 to 255.</span></span><br><span class="line">&lt;bytes&gt; = bytes(&lt;str&gt;, <span class="string">'utf-8'</span>)          <span class="comment"># Or: &lt;str&gt;.encode('utf-8')</span></span><br><span class="line">&lt;bytes&gt; = &lt;int&gt;.to_bytes(n_bytes, byteorder=<span class="string">'big|little'</span>, signed=<span class="literal">False</span>)</span><br><span class="line">&lt;bytes&gt; = bytes.fromhex(<span class="string">'&lt;hex&gt;'</span>)</span><br></pre></td></tr></table></figure>
<h3 id="Decode-1"><a href="#Decode-1" class="headerlink" title="Decode"></a>Decode</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;list&gt;  = list(&lt;bytes&gt;)                  <span class="comment"># Returns ints in range from 0 to 255.</span></span><br><span class="line">&lt;str&gt;   = str(&lt;bytes&gt;, <span class="string">'utf-8'</span>)          <span class="comment"># Or: &lt;bytes&gt;.decode('utf-8')</span></span><br><span class="line">&lt;int&gt;   = int.from_bytes(&lt;bytes&gt;, byteorder=<span class="string">'big|little'</span>, signed=<span class="literal">False</span>)</span><br><span class="line"><span class="string">'&lt;hex&gt;'</span> = &lt;bytes&gt;.hex()</span><br></pre></td></tr></table></figure>
<h3 id="Read-Bytes-from-File"><a href="#Read-Bytes-from-File" class="headerlink" title="Read Bytes from File"></a>Read Bytes from File</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">read_bytes</span><span class="params">(filename)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> open(filename, <span class="string">'rb'</span>) <span class="keyword">as</span> file:</span><br><span class="line">        <span class="keyword">return</span> file.read()</span><br></pre></td></tr></table></figure>
<h3 id="Write-Bytes-to-File"><a href="#Write-Bytes-to-File" class="headerlink" title="Write Bytes to File"></a>Write Bytes to File</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">write_bytes</span><span class="params">(filename, bytes_obj)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> open(filename, <span class="string">'wb'</span>) <span class="keyword">as</span> file:</span><br><span class="line">        file.write(bytes_obj)</span><br></pre></td></tr></table></figure>
<h2 id="Struct"><a href="#Struct" class="headerlink" title="Struct"></a>Struct</h2><ul>
<li><strong>Module that performs conversions between a sequence of numbers and a bytes object.</strong></li>
<li><strong>Machine’s native type sizes and byte order are used by default.</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> struct <span class="keyword">import</span> pack, unpack, iter_unpack</span><br><span class="line">&lt;bytes&gt;  = pack(<span class="string">'&lt;format&gt;'</span>, &lt;num_1&gt; [, &lt;num_2&gt;, ...])</span><br><span class="line">&lt;tuple&gt;  = unpack(<span class="string">'&lt;format&gt;'</span>, &lt;bytes&gt;)</span><br><span class="line">&lt;tuples&gt; = iter_unpack(<span class="string">'&lt;format&gt;'</span>, &lt;bytes&gt;)</span><br></pre></td></tr></table></figure>
<h3 id="Example-1"><a href="#Example-1" class="headerlink" title="Example"></a>Example</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>pack(<span class="string">'&gt;hhl'</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line"><span class="string">b'\x00\x01\x00\x02\x00\x00\x00\x03'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>unpack(<span class="string">'&gt;hhl'</span>, <span class="string">b'\x00\x01\x00\x02\x00\x00\x00\x03'</span>)</span><br><span class="line">(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</span><br></pre></td></tr></table></figure>
<h3 id="Format-2"><a href="#Format-2" class="headerlink" title="Format"></a>Format</h3><h4 id="For-standard-sizes-start-format-string-with"><a href="#For-standard-sizes-start-format-string-with" class="headerlink" title="For standard sizes start format string with:"></a>For standard sizes start format string with:</h4><ul>
<li><strong><code>&#39;=&#39;</code> - native byte order</strong></li>
<li><strong><code>&#39;&lt;&#39;</code> - little-endian</strong></li>
<li><strong><code>&#39;&gt;&#39;</code> - big-endian (also <code>&#39;!&#39;</code>)</strong></li>
</ul>
<h4 id="Integer-types-Use-capital-letter-for-unsigned-type-Standard-sizes-are-in-brackets"><a href="#Integer-types-Use-capital-letter-for-unsigned-type-Standard-sizes-are-in-brackets" class="headerlink" title="Integer types. Use capital letter for unsigned type. Standard sizes are in brackets:"></a>Integer types. Use capital letter for unsigned type. Standard sizes are in brackets:</h4><ul>
<li><strong><code>&#39;x&#39;</code> - pad byte</strong></li>
<li><strong><code>&#39;b&#39;</code> - char (1)</strong></li>
<li><strong><code>&#39;h&#39;</code> - short (2)</strong></li>
<li><strong><code>&#39;i&#39;</code> - int (4)</strong></li>
<li><strong><code>&#39;l&#39;</code> - long (4)</strong></li>
<li><strong><code>&#39;q&#39;</code> - long long (8)</strong></li>
</ul>
<h4 id="Floating-point-types"><a href="#Floating-point-types" class="headerlink" title="Floating point types:"></a>Floating point types:</h4><ul>
<li><strong><code>&#39;f&#39;</code> - float (4)</strong></li>
<li><strong><code>&#39;d&#39;</code> - double (8)</strong></li>
</ul>
<h2 id="Array"><a href="#Array" class="headerlink" title="Array"></a>Array</h2><p><strong>List that can only hold numbers of a predefined type. Available types and their sizes in bytes are listed above.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> array <span class="keyword">import</span> array</span><br><span class="line">&lt;array&gt; = array(<span class="string">'&lt;typecode&gt;'</span>, &lt;collection&gt;)    <span class="comment"># Array from coll. of numbers.</span></span><br><span class="line">&lt;array&gt; = array(<span class="string">'&lt;typecode&gt;'</span>, &lt;bytes&gt;)         <span class="comment"># Array from bytes object.</span></span><br><span class="line">&lt;bytes&gt; = bytes(&lt;array&gt;)                       <span class="comment"># Or: &lt;array&gt;.tobytes()</span></span><br></pre></td></tr></table></figure>
<h2 id="Memory-View"><a href="#Memory-View" class="headerlink" title="Memory View"></a>Memory View</h2><ul>
<li><strong>A sequence object that points to the memory of another object.</strong></li>
<li><strong>Each element can reference a single or multiple consecutive bytes, depending on format.</strong></li>
<li><strong>Order and number of elements can be changed with slicing.</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;mview&gt; = memoryview(&lt;bytes/bytearray/array&gt;)  <span class="comment"># Immutable if bytes, else mutable.</span></span><br><span class="line">&lt;real&gt;  = &lt;mview&gt;[&lt;index&gt;]                     <span class="comment"># Returns an int or a float.</span></span><br><span class="line">&lt;mview&gt; = &lt;mview&gt;[&lt;slice&gt;]                     <span class="comment"># Mview with rearranged elements.</span></span><br><span class="line">&lt;mview&gt; = &lt;mview&gt;.cast(<span class="string">'&lt;typecode&gt;'</span>)           <span class="comment"># Casts memoryview to the new format.</span></span><br><span class="line">&lt;mview&gt;.release()                              <span class="comment"># Releases the object's memory buffer.</span></span><br></pre></td></tr></table></figure>
<h3 id="Decode-2"><a href="#Decode-2" class="headerlink" title="Decode"></a>Decode</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;bin_file&gt;.write(&lt;mview&gt;)                      <span class="comment"># Appends mview to the binary file.</span></span><br><span class="line">&lt;bytes&gt; = bytes(&lt;mview&gt;)                       <span class="comment"># Creates a new bytes object.</span></span><br><span class="line">&lt;bytes&gt; = &lt;bytes&gt;.join(&lt;coll_of_mviews&gt;)       <span class="comment"># Joins mviews using bytes object as sep.</span></span><br><span class="line">&lt;list&gt;  = list(&lt;mview&gt;)                        <span class="comment"># Returns list of ints or floats.</span></span><br><span class="line">&lt;str&gt;   = str(&lt;mview&gt;, <span class="string">'utf-8'</span>)</span><br><span class="line">&lt;int&gt;   = int.from_bytes(&lt;mview&gt;, byteorder=<span class="string">'big|little'</span>, signed=<span class="literal">False</span>)</span><br><span class="line"><span class="string">'&lt;hex&gt;'</span> = &lt;mview&gt;.hex()</span><br></pre></td></tr></table></figure>
<h2 id="Deque"><a href="#Deque" class="headerlink" title="Deque"></a>Deque</h2><p><strong>A thread-safe list with efficient appends and pops from either side. Pronounced “deck”.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> deque</span><br><span class="line">&lt;deque&gt; = deque(&lt;collection&gt;, maxlen=<span class="literal">None</span>)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;deque&gt;.appendleft(&lt;el&gt;)                       <span class="comment"># Opposite element is dropped if full.</span></span><br><span class="line">&lt;el&gt; = &lt;deque&gt;.popleft()                       <span class="comment"># Raises IndexError if empty.</span></span><br><span class="line">&lt;deque&gt;.extendleft(&lt;collection&gt;)               <span class="comment"># Collection gets reversed.</span></span><br><span class="line">&lt;deque&gt;.rotate(n=<span class="number">1</span>)                            <span class="comment"># Rotates elements to the right.</span></span><br></pre></td></tr></table></figure>
<h2 id="Threading"><a href="#Threading" class="headerlink" title="Threading"></a>Threading</h2><ul>
<li><strong>CPython interpreter can only run a single thread at a time.</strong></li>
<li><strong>That is why using multiple threads won’t result in a faster execution, unless there is an I/O operation in the thread.</strong><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> threading <span class="keyword">import</span> Thread, RLock</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="Thread"><a href="#Thread" class="headerlink" title="Thread"></a>Thread</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">thread = Thread(target=&lt;function&gt;, args=(&lt;first_arg&gt;, ))</span><br><span class="line">thread.start()</span><br><span class="line">...</span><br><span class="line">&lt;bool&gt; = thread.is_alive()           <span class="comment"># Checks if thread has finished executing.</span></span><br><span class="line">thread.join()                        <span class="comment"># Waits for thread to finish.</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Use <code>&#39;kwargs=&lt;dict&gt;&#39;</code> to pass keyword arguments to the function.</strong></li>
<li><strong>Use <code>&#39;daemon=True&#39;</code>, or the program will not be able to exit while the thread is alive.</strong></li>
</ul>
<h3 id="Lock"><a href="#Lock" class="headerlink" title="Lock"></a>Lock</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">lock = RLock()</span><br><span class="line">lock.acquire()                       <span class="comment"># Waits for lock to be available.</span></span><br><span class="line">...</span><br><span class="line">lock.release()</span><br></pre></td></tr></table></figure>
<h4 id="Or-1"><a href="#Or-1" class="headerlink" title="Or:"></a>Or:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">lock = RLock()</span><br><span class="line"><span class="keyword">with</span> lock:</span><br><span class="line">    ...</span><br></pre></td></tr></table></figure>
<h3 id="Thread-Pool-Executor"><a href="#Thread-Pool-Executor" class="headerlink" title="Thread Pool Executor"></a>Thread Pool Executor</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> concurrent.futures <span class="keyword">import</span> ThreadPoolExecutor</span><br><span class="line"><span class="keyword">with</span> ThreadPoolExecutor(max_workers=<span class="literal">None</span>) <span class="keyword">as</span> executor:</span><br><span class="line">    &lt;iter&gt;   = executor.map(<span class="keyword">lambda</span> x: x + <span class="number">1</span>, range(<span class="number">3</span>))         <span class="comment"># (1, 2, 3)</span></span><br><span class="line">    &lt;iter&gt;   = executor.map(<span class="keyword">lambda</span> x, y: x + y, <span class="string">'abc'</span>, <span class="string">'123'</span>)  <span class="comment"># ('a1', 'b2', 'c3')</span></span><br><span class="line">    &lt;Future&gt; = executor.submit(&lt;function&gt; [, &lt;arg_1&gt;, ...])</span><br></pre></td></tr></table></figure>
<h4 id="Future"><a href="#Future" class="headerlink" title="Future:"></a>Future:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;bool&gt; = &lt;Future&gt;.done()             <span class="comment"># Checks if thread has finished executing.</span></span><br><span class="line">&lt;obj&gt;  = &lt;Future&gt;.result()           <span class="comment"># Waits for thread to finish and returns result.</span></span><br></pre></td></tr></table></figure>
<h3 id="Queue"><a href="#Queue" class="headerlink" title="Queue"></a>Queue</h3><p><strong>A thread-safe FIFO queue. For LIFO queue use LifoQueue.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> queue <span class="keyword">import</span> Queue</span><br><span class="line">&lt;Queue&gt; = Queue(maxsize=<span class="number">0</span>)</span><br></pre></td></tr></table></figure></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;Queue&gt;.put(&lt;el&gt;)                    <span class="comment"># Blocks until queue stops being full.</span></span><br><span class="line">&lt;Queue&gt;.put_nowait(&lt;el&gt;)             <span class="comment"># Raises queue.Full exception if full.</span></span><br><span class="line">&lt;el&gt; = &lt;Queue&gt;.get()                 <span class="comment"># Blocks until queue stops being empty.</span></span><br><span class="line">&lt;el&gt; = &lt;Queue&gt;.get_nowait()          <span class="comment"># Raises _queue.Empty exception if empty.</span></span><br></pre></td></tr></table></figure>
<h2 id="Operator"><a href="#Operator" class="headerlink" title="Operator"></a>Operator</h2><p><strong>Module of functions that provide the functionality of operators.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> operator <span class="keyword">import</span> add, sub, mul, truediv, floordiv, mod, pow, neg, abs</span><br><span class="line"><span class="keyword">from</span> operator <span class="keyword">import</span> eq, ne, lt, le, gt, ge</span><br><span class="line"><span class="keyword">from</span> operator <span class="keyword">import</span> and_, or_, not_</span><br><span class="line"><span class="keyword">from</span> operator <span class="keyword">import</span> itemgetter, attrgetter, methodcaller</span><br></pre></td></tr></table></figure></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> operator <span class="keyword">as</span> op</span><br><span class="line">sorted_by_second = sorted(&lt;collection&gt;, key=op.itemgetter(<span class="number">1</span>))</span><br><span class="line">sorted_by_both   = sorted(&lt;collection&gt;, key=op.itemgetter(<span class="number">1</span>, <span class="number">0</span>))</span><br><span class="line">product_of_elems = functools.reduce(op.mul, &lt;collection&gt;)</span><br><span class="line">LogicOp          = enum.Enum(<span class="string">'LogicOp'</span>, &#123;<span class="string">'AND'</span>: op.and_, <span class="string">'OR'</span> : op.or_&#125;)</span><br><span class="line">last_el          = op.methodcaller(<span class="string">'pop'</span>)(&lt;list&gt;)</span><br></pre></td></tr></table></figure>
<h2 id="Introspection"><a href="#Introspection" class="headerlink" title="Introspection"></a>Introspection</h2><p><strong>Inspecting code at runtime.</strong></p>
<h3 id="Variables"><a href="#Variables" class="headerlink" title="Variables"></a>Variables</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;list&gt; = dir()                       <span class="comment"># Returns names of variables in current scope.</span></span><br><span class="line">&lt;dict&gt; = locals()                    <span class="comment"># Returns dict of local variables. Also vars().</span></span><br><span class="line">&lt;dict&gt; = globals()                   <span class="comment"># Returns dict of global variables.</span></span><br></pre></td></tr></table></figure>
<h3 id="Attributes-1"><a href="#Attributes-1" class="headerlink" title="Attributes"></a>Attributes</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;dict&gt; = vars(&lt;object&gt;)</span><br><span class="line">&lt;bool&gt; = hasattr(&lt;object&gt;, <span class="string">'&lt;attr_name&gt;'</span>)</span><br><span class="line">value  = getattr(&lt;object&gt;, <span class="string">'&lt;attr_name&gt;'</span>)</span><br><span class="line">setattr(&lt;object&gt;, <span class="string">'&lt;attr_name&gt;'</span>, value)</span><br></pre></td></tr></table></figure>
<h3 id="Parameters-1"><a href="#Parameters-1" class="headerlink" title="Parameters"></a>Parameters</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> inspect <span class="keyword">import</span> signature</span><br><span class="line">&lt;sig&gt;        = signature(&lt;function&gt;)</span><br><span class="line">no_of_params = len(&lt;sig&gt;.parameters)</span><br><span class="line">param_names  = list(&lt;sig&gt;.parameters.keys())</span><br></pre></td></tr></table></figure>
<h2 id="Metaprograming"><a href="#Metaprograming" class="headerlink" title="Metaprograming"></a>Metaprograming</h2><p><strong>Code that generates code.</strong></p>
<h3 id="Type-1"><a href="#Type-1" class="headerlink" title="Type"></a>Type</h3><p><strong>Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.</strong></p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;class&gt; = type('&lt;class_name&gt;', &lt;parents_tuple&gt;, &lt;attributes_dict&gt;)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>Z = type(<span class="string">'Z'</span>, (), &#123;<span class="string">'a'</span>: <span class="string">'abcde'</span>, <span class="string">'b'</span>: <span class="number">12345</span>&#125;)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>z = Z()</span><br></pre></td></tr></table></figure>
<h3 id="Meta-Class"><a href="#Meta-Class" class="headerlink" title="Meta Class"></a>Meta Class</h3><p><strong>Class that creates classes.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">my_meta_class</span><span class="params">(name, parents, attrs)</span>:</span></span><br><span class="line">    attrs[<span class="string">'a'</span>] = <span class="string">'abcde'</span></span><br><span class="line">    <span class="keyword">return</span> type(name, parents, attrs)</span><br></pre></td></tr></table></figure>
<h4 id="Or-2"><a href="#Or-2" class="headerlink" title="Or:"></a>Or:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyMetaClass</span><span class="params">(type)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__new__</span><span class="params">(cls, name, parents, attrs)</span>:</span></span><br><span class="line">        attrs[<span class="string">'a'</span>] = <span class="string">'abcde'</span></span><br><span class="line">        <span class="keyword">return</span> type.__new__(cls, name, parents, attrs)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a ‘self’ argument.</strong></li>
<li><strong>It receives the same arguments as init(), except for the first one that specifies the desired type of the returned instance (MyMetaClass in our case).</strong></li>
<li><strong>Like in our case, new() can also be called directly, usually from a new() method of a child class (</strong><code>def __new__(cls): return super().__new__(cls)</code><strong>).</strong></li>
<li><strong>The only difference between the examples above is that my_meta_class() returns a class of type type, while MyMetaClass() returns a class of type MyMetaClass.</strong></li>
</ul>
<h3 id="Metaclass-Attribute"><a href="#Metaclass-Attribute" class="headerlink" title="Metaclass Attribute"></a>Metaclass Attribute</h3><p><strong>Right before a class is created it checks if it has a ‘metaclass’ attribute defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type().</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyClass</span><span class="params">(metaclass=MyMetaClass)</span>:</span></span><br><span class="line">    b = <span class="number">12345</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>MyClass.a, MyClass.b</span><br><span class="line">(<span class="string">'abcde'</span>, <span class="number">12345</span>)</span><br></pre></td></tr></table></figure>
<h3 id="Type-Diagram"><a href="#Type-Diagram" class="headerlink" title="Type Diagram"></a>Type Diagram</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">type(MyClass)     == MyMetaClass     <span class="comment"># MyClass is an instance of MyMetaClass.</span></span><br><span class="line">type(MyMetaClass) == type            <span class="comment"># MyMetaClass is an instance of type.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">+-------------+-------------+</span><br><span class="line">|   Classes   | Metaclasses |</span><br><span class="line">+-------------+-------------|</span><br><span class="line">|   MyClass --&gt; MyMetaClass |</span><br><span class="line">|             |     v       |</span><br><span class="line">|    object -----&gt; type &lt;+  |</span><br><span class="line">|             |    ^ +---+  |</span><br><span class="line">|     str ---------+        |</span><br><span class="line">+-------------+-------------+</span><br></pre></td></tr></table></figure>
<h3 id="Inheritance-Diagram"><a href="#Inheritance-Diagram" class="headerlink" title="Inheritance Diagram"></a>Inheritance Diagram</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">MyClass.__base__     == object       <span class="comment"># MyClass is a subclass of object.</span></span><br><span class="line">MyMetaClass.__base__ == type         <span class="comment"># MyMetaClass is a subclass of type.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">+-------------+-------------+</span><br><span class="line">|   Classes   | Metaclasses |</span><br><span class="line">+-------------+-------------|</span><br><span class="line">|   MyClass   | MyMetaClass |</span><br><span class="line">|      v      |     v       |</span><br><span class="line">|    object &lt;----- type     |</span><br><span class="line">|      ^      |             |</span><br><span class="line">|     str     |             |</span><br><span class="line">+-------------+-------------+</span><br></pre></td></tr></table></figure>
<h2 id="Eval"><a href="#Eval" class="headerlink" title="Eval"></a>Eval</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> ast <span class="keyword">import</span> literal_eval</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>literal_eval(<span class="string">'1 + 2'</span>)</span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>literal_eval(<span class="string">'[1, 2, 3]'</span>)</span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>literal_eval(<span class="string">'abs(1)'</span>)</span><br><span class="line">ValueError: malformed node <span class="keyword">or</span> string</span><br></pre></td></tr></table></figure>
<h2 id="Coroutine"><a href="#Coroutine" class="headerlink" title="Coroutine"></a>Coroutine</h2><ul>
<li><strong>Any function that contains a <code>&#39;(yield)&#39;</code> expression returns a coroutine.</strong></li>
<li><strong>Coroutines are similar to iterators, but data needs to be pulled out of an iterator by calling <code>&#39;next(&lt;iter&gt;)&#39;</code>, while we push data into the coroutine by calling <code>&#39;&lt;coroutine&gt;.send(&lt;el&gt;)&#39;</code>.</strong></li>
<li><strong>Coroutines provide more powerful data routing possibilities than iterators.</strong></li>
</ul>
<h3 id="Helper-Decorator"><a href="#Helper-Decorator" class="headerlink" title="Helper Decorator"></a>Helper Decorator</h3><ul>
<li><strong>All coroutines must first be “primed” by calling <code>&#39;next(&lt;coroutine&gt;)&#39;</code>.</strong></li>
<li><strong>Remembering to call next() is easy to forget.</strong></li>
<li><strong>Solved by wrapping coroutine functions with the following decorator:</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">coroutine</span><span class="params">(func)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">out</span><span class="params">(*args, **kwargs)</span>:</span></span><br><span class="line">        cr = func(*args, **kwargs)</span><br><span class="line">        next(cr)</span><br><span class="line">        <span class="keyword">return</span> cr</span><br><span class="line">    <span class="keyword">return</span> out</span><br></pre></td></tr></table></figure>
<h3 id="Pipeline-Example"><a href="#Pipeline-Example" class="headerlink" title="Pipeline Example"></a>Pipeline Example</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">reader</span><span class="params">(target)</span>:</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>):</span><br><span class="line">        target.send(i)</span><br><span class="line">    target.close()</span><br><span class="line"></span><br><span class="line"><span class="meta">@coroutine</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">adder</span><span class="params">(target)</span>:</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        value = (<span class="keyword">yield</span>)</span><br><span class="line">        target.send(value + <span class="number">100</span>)</span><br><span class="line"></span><br><span class="line"><span class="meta">@coroutine</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">printer</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        value = (<span class="keyword">yield</span>)</span><br><span class="line">        print(value, end=<span class="string">' '</span>)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>reader(adder(printer()))</span><br><span class="line"><span class="number">100</span> <span class="number">101</span> <span class="number">102</span> <span class="number">103</span> <span class="number">104</span> <span class="number">105</span> <span class="number">106</span> <span class="number">107</span> <span class="number">108</span> <span class="number">109</span></span><br></pre></td></tr></table></figure>
<p><br></p>
<h1 id="Libraries"><a href="#Libraries" class="headerlink" title="Libraries"></a>Libraries</h1><h2 id="Progress-Bar"><a href="#Progress-Bar" class="headerlink" title="Progress Bar"></a>Progress Bar</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install tqdm</span></span><br><span class="line"><span class="keyword">from</span> tqdm <span class="keyword">import</span> tqdm</span><br><span class="line"><span class="keyword">from</span> time <span class="keyword">import</span> sleep</span><br><span class="line"><span class="keyword">for</span> el <span class="keyword">in</span> tqdm([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]):</span><br><span class="line">    sleep(<span class="number">0.2</span>)</span><br></pre></td></tr></table></figure>
<h2 id="Plot"><a href="#Plot" class="headerlink" title="Plot"></a>Plot</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install matplotlib</span></span><br><span class="line"><span class="keyword">from</span> matplotlib <span class="keyword">import</span> pyplot</span><br><span class="line">pyplot.plot(&lt;y_data&gt; [, label=&lt;str&gt;])</span><br><span class="line">pyplot.plot(&lt;x_data&gt;, &lt;y_data&gt;)</span><br><span class="line">pyplot.legend()                                <span class="comment"># Adds a legend.</span></span><br><span class="line">pyplot.savefig(&lt;filename&gt;)                     <span class="comment"># Saves the figure.</span></span><br><span class="line">pyplot.show()                                  <span class="comment"># Displays the figure.</span></span><br><span class="line">pyplot.clf()                                   <span class="comment"># Clears the figure.</span></span><br></pre></td></tr></table></figure>
<h2 id="Table"><a href="#Table" class="headerlink" title="Table"></a>Table</h2><h4 id="Prints-a-CSV-file-as-an-ASCII-table"><a href="#Prints-a-CSV-file-as-an-ASCII-table" class="headerlink" title="Prints a CSV file as an ASCII table:"></a>Prints a CSV file as an ASCII table:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install tabulate</span></span><br><span class="line"><span class="keyword">import</span> csv, tabulate</span><br><span class="line"><span class="keyword">with</span> open(<span class="string">'test.csv'</span>, encoding=<span class="string">'utf-8'</span>, newline=<span class="string">''</span>) <span class="keyword">as</span> file:</span><br><span class="line">    rows   = csv.reader(file)</span><br><span class="line">    header = [a.title() <span class="keyword">for</span> a <span class="keyword">in</span> next(rows)]</span><br><span class="line">    table  = tabulate.tabulate(rows, header)</span><br><span class="line">    print(table)</span><br></pre></td></tr></table></figure>
<h2 id="Curses"><a href="#Curses" class="headerlink" title="Curses"></a>Curses</h2><h4 id="Clears-the-terminal-prints-a-message-and-waits-for-an-ESC-key-press"><a href="#Clears-the-terminal-prints-a-message-and-waits-for-an-ESC-key-press" class="headerlink" title="Clears the terminal, prints a message and waits for an ESC key press:"></a>Clears the terminal, prints a message and waits for an ESC key press:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> curses <span class="keyword">import</span> wrapper, curs_set, ascii</span><br><span class="line"><span class="keyword">from</span> curses <span class="keyword">import</span> KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_LEFT</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    wrapper(draw)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">draw</span><span class="params">(screen)</span>:</span></span><br><span class="line">    curs_set(<span class="number">0</span>)                                <span class="comment"># Makes cursor invisible.</span></span><br><span class="line">    screen.nodelay(<span class="literal">True</span>)                       <span class="comment"># Makes getch() non-blocking.</span></span><br><span class="line">    screen.clear()</span><br><span class="line">    screen.addstr(<span class="number">0</span>, <span class="number">0</span>, <span class="string">'Press ESC to quit.'</span>)</span><br><span class="line">    <span class="keyword">while</span> screen.getch() != ascii.ESC:</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_border</span><span class="params">(screen)</span>:</span></span><br><span class="line">    <span class="keyword">from</span> collections <span class="keyword">import</span> namedtuple</span><br><span class="line">    P = namedtuple(<span class="string">'P'</span>, <span class="string">'x y'</span>)</span><br><span class="line">    height, width = screen.getmaxyx()</span><br><span class="line">    <span class="keyword">return</span> P(width - <span class="number">1</span>, height - <span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>
<h2 id="Logging"><a href="#Logging" class="headerlink" title="Logging"></a>Logging</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install loguru</span></span><br><span class="line"><span class="keyword">from</span> loguru <span class="keyword">import</span> logger</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">logger.add(<span class="string">'debug_&#123;time&#125;.log'</span>, colorize=<span class="literal">True</span>)  <span class="comment"># Connects a log file.</span></span><br><span class="line">logger.add(<span class="string">'error_&#123;time&#125;.log'</span>, level=<span class="string">'ERROR'</span>)  <span class="comment"># Another file for errors or higher.</span></span><br><span class="line">logger.&lt;level&gt;(<span class="string">'A logging message.'</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Levels: <code>&#39;debug&#39;</code>, <code>&#39;info&#39;</code>, <code>&#39;success&#39;</code>, <code>&#39;warning&#39;</code>, <code>&#39;error&#39;</code>, <code>&#39;critical&#39;</code>.</strong></li>
</ul>
<h3 id="Exceptions-2"><a href="#Exceptions-2" class="headerlink" title="Exceptions"></a>Exceptions</h3><p><strong>Exception description, stack trace and values of variables are appended automatically.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    ...</span><br><span class="line"><span class="keyword">except</span> &lt;exception&gt;:</span><br><span class="line">    logger.exception(<span class="string">'An error happened.'</span>)</span><br></pre></td></tr></table></figure>
<h3 id="Rotation"><a href="#Rotation" class="headerlink" title="Rotation"></a>Rotation</h3><p><strong>Argument that sets a condition when a new log file is created.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">rotation=&lt;int&gt;|&lt;datetime.timedelta&gt;|&lt;datetime.time&gt;|&lt;str&gt;</span><br></pre></td></tr></table></figure></p>
<ul>
<li><strong><code>&#39;&lt;int&gt;&#39;</code> - Max file size in bytes.</strong></li>
<li><strong><code>&#39;&lt;timedelta&gt;&#39;</code> - Max age of a file.</strong></li>
<li><strong><code>&#39;&lt;time&gt;&#39;</code> - Time of day.</strong></li>
<li><strong><code>&#39;&lt;str&gt;&#39;</code> - Any of above as a string: <code>&#39;100 MB&#39;</code>, <code>&#39;1 month&#39;</code>, <code>&#39;monday at 12:00&#39;</code>, …</strong></li>
</ul>
<h3 id="Retention"><a href="#Retention" class="headerlink" title="Retention"></a>Retention</h3><p><strong>Sets a condition which old log files get deleted.</strong><br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">retention=&lt;int&gt;|&lt;datetime.timedelta&gt;|&lt;str&gt;</span><br></pre></td></tr></table></figure></p>
<ul>
<li><strong><code>&#39;&lt;int&gt;&#39;</code> - Max number of files.</strong></li>
<li><strong><code>&#39;&lt;timedelta&gt;&#39;</code> - Max age of a file.</strong></li>
<li><strong><code>&#39;&lt;str&gt;&#39;</code> - Max age as a string: <code>&#39;1 week, 3 days&#39;</code>, <code>&#39;2 months&#39;</code>, …</strong></li>
</ul>
<h2 id="Scraping"><a href="#Scraping" class="headerlink" title="Scraping"></a>Scraping</h2><h4 id="Scrapes-Python’s-URL-version-number-and-logo-from-Wikipedia-page"><a href="#Scrapes-Python’s-URL-version-number-and-logo-from-Wikipedia-page" class="headerlink" title="Scrapes Python’s URL, version number and logo from Wikipedia page:"></a>Scrapes Python’s URL, version number and logo from Wikipedia page:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install requests beautifulsoup4</span></span><br><span class="line"><span class="keyword">import</span> requests</span><br><span class="line"><span class="keyword">from</span> bs4 <span class="keyword">import</span> BeautifulSoup</span><br><span class="line">URL = <span class="string">'https://en.wikipedia.org/wiki/Python_(programming_language)'</span></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    html  = requests.get(URL).text</span><br><span class="line">    doc   = BeautifulSoup(html, <span class="string">'html.parser'</span>)</span><br><span class="line">    table = doc.find(<span class="string">'table'</span>, class_=<span class="string">'infobox vevent'</span>)</span><br><span class="line">    rows  = table.find_all(<span class="string">'tr'</span>)</span><br><span class="line">    link  = rows[<span class="number">11</span>].find(<span class="string">'a'</span>)[<span class="string">'href'</span>]</span><br><span class="line">    ver   = rows[<span class="number">6</span>].find(<span class="string">'div'</span>).text.split()[<span class="number">0</span>]</span><br><span class="line">    url_i = rows[<span class="number">0</span>].find(<span class="string">'img'</span>)[<span class="string">'src'</span>]</span><br><span class="line">    image = requests.get(<span class="string">f'https:<span class="subst">&#123;url_i&#125;</span>'</span>).content</span><br><span class="line">    <span class="keyword">with</span> open(<span class="string">'test.png'</span>, <span class="string">'wb'</span>) <span class="keyword">as</span> file:</span><br><span class="line">        file.write(image)</span><br><span class="line">    print(link, ver)</span><br><span class="line"><span class="keyword">except</span> requests.exceptions.ConnectionError:</span><br><span class="line">    print(<span class="string">"You've got problems with connection."</span>)</span><br></pre></td></tr></table></figure>
<h2 id="Web"><a href="#Web" class="headerlink" title="Web"></a>Web</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install bottle</span></span><br><span class="line"><span class="keyword">from</span> bottle <span class="keyword">import</span> run, route, static_file, template, post, request, response</span><br><span class="line"><span class="keyword">import</span> json</span><br></pre></td></tr></table></figure>
<h3 id="Run"><a href="#Run" class="headerlink" title="Run"></a>Run</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">run(host=<span class="string">'localhost'</span>, port=<span class="number">8080</span>)        <span class="comment"># Runs locally.</span></span><br><span class="line">run(host=<span class="string">'0.0.0.0'</span>, port=<span class="number">80</span>)            <span class="comment"># Runs globally.</span></span><br></pre></td></tr></table></figure>
<h3 id="Static-Request"><a href="#Static-Request" class="headerlink" title="Static Request"></a>Static Request</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@route('/img/&lt;image&gt;')</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">send_image</span><span class="params">(image)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> static_file(image, <span class="string">'img_dir/'</span>, mimetype=<span class="string">'image/png'</span>)</span><br></pre></td></tr></table></figure>
<h3 id="Dynamic-Request"><a href="#Dynamic-Request" class="headerlink" title="Dynamic Request"></a>Dynamic Request</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@route('/&lt;sport&gt;')</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">send_page</span><span class="params">(sport)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> template(<span class="string">'&lt;h1&gt;&#123;&#123;title&#125;&#125;&lt;/h1&gt;'</span>, title=sport)</span><br></pre></td></tr></table></figure>
<h3 id="REST-Request"><a href="#REST-Request" class="headerlink" title="REST Request"></a>REST Request</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@post('/odds/&lt;sport&gt;')</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">odds_handler</span><span class="params">(sport)</span>:</span></span><br><span class="line">    team = request.forms.get(<span class="string">'team'</span>)</span><br><span class="line">    home_odds, away_odds = <span class="number">2.44</span>, <span class="number">3.29</span></span><br><span class="line">    response.headers[<span class="string">'Content-Type'</span>] = <span class="string">'application/json'</span></span><br><span class="line">    response.headers[<span class="string">'Cache-Control'</span>] = <span class="string">'no-cache'</span></span><br><span class="line">    <span class="keyword">return</span> json.dumps([team, home_odds, away_odds])</span><br></pre></td></tr></table></figure>
<h4 id="Test"><a href="#Test" class="headerlink" title="Test:"></a>Test:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install requests</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> requests</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>url  = <span class="string">'http://localhost:8080/odds/football'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>data = &#123;<span class="string">'team'</span>: <span class="string">'arsenal f.c.'</span>&#125;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>response = requests.post(url, data=data)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>response.json()</span><br><span class="line">[<span class="string">'arsenal f.c.'</span>, <span class="number">2.44</span>, <span class="number">3.29</span>]</span><br></pre></td></tr></table></figure>
<h2 id="Profiling"><a href="#Profiling" class="headerlink" title="Profiling"></a>Profiling</h2><h3 id="Stopwatch"><a href="#Stopwatch" class="headerlink" title="Stopwatch"></a>Stopwatch</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> time <span class="keyword">import</span> time</span><br><span class="line">start_time = time()                     <span class="comment"># Seconds since the Epoch.</span></span><br><span class="line">...</span><br><span class="line">duration = time() - start_time</span><br></pre></td></tr></table></figure>
<h4 id="High-performance"><a href="#High-performance" class="headerlink" title="High performance:"></a>High performance:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> time <span class="keyword">import</span> perf_counter</span><br><span class="line">start_time = perf_counter()             <span class="comment"># Seconds since restart.</span></span><br><span class="line">...</span><br><span class="line">duration = perf_counter() - start_time</span><br></pre></td></tr></table></figure>
<h3 id="Timing-a-Snippet"><a href="#Timing-a-Snippet" class="headerlink" title="Timing a Snippet"></a>Timing a Snippet</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> timeit <span class="keyword">import</span> timeit</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>timeit(<span class="string">'"-".join(str(a) for a in range(100))'</span>,</span><br><span class="line"><span class="meta">... </span>       number=<span class="number">10000</span>, globals=globals(), setup=<span class="string">'pass'</span>)</span><br><span class="line"><span class="number">0.34986</span></span><br></pre></td></tr></table></figure>
<h3 id="Profiling-by-Line"><a href="#Profiling-by-Line" class="headerlink" title="Profiling by Line"></a>Profiling by Line</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install line_profiler memory_profiler</span></span><br><span class="line"><span class="meta">@profile</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    a = [*range(<span class="number">10000</span>)]</span><br><span class="line">    b = &#123;*range(<span class="number">10000</span>)&#125;</span><br><span class="line">main()</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">$ kernprof -lv test.py</span><br><span class="line">Line #   Hits     Time  Per Hit   % Time  Line Contents</span><br><span class="line">=======================================================</span><br><span class="line">     1                                    @profile</span><br><span class="line">     2                                    def main():</span><br><span class="line">     3      1   1128.0   1128.0     27.4      a = [*range(10000)]</span><br><span class="line">     4      1   2994.0   2994.0     72.6      b = &#123;*range(10000)&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">$ python3 -m memory_profiler test.py</span><br><span class="line">Line #         Mem usage      Increment   Line Contents</span><br><span class="line">=======================================================</span><br><span class="line">     1        35.387 MiB     35.387 MiB   @profile</span><br><span class="line">     2                                    def main():</span><br><span class="line">     3        35.734 MiB      0.348 MiB       a = [*range(10000)]</span><br><span class="line">     4        36.160 MiB      0.426 MiB       b = &#123;*range(10000)&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Call-Graph"><a href="#Call-Graph" class="headerlink" title="Call Graph"></a>Call Graph</h3><h4 id="Generates-a-PNG-image-of-a-call-graph-with-highlighted-bottlenecks"><a href="#Generates-a-PNG-image-of-a-call-graph-with-highlighted-bottlenecks" class="headerlink" title="Generates a PNG image of a call graph with highlighted bottlenecks:"></a>Generates a PNG image of a call graph with highlighted bottlenecks:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install pycallgraph</span></span><br><span class="line"><span class="keyword">from</span> pycallgraph <span class="keyword">import</span> output, PyCallGraph</span><br><span class="line"><span class="keyword">from</span> datetime <span class="keyword">import</span> datetime</span><br><span class="line">time_str = datetime.now().strftime(<span class="string">'%Y%m%d%H%M%S'</span>)</span><br><span class="line">filename = <span class="string">f'profile-<span class="subst">&#123;time_str&#125;</span>.png'</span></span><br><span class="line">drawer = output.GraphvizOutput(output_file=filename)</span><br><span class="line"><span class="keyword">with</span> PyCallGraph(drawer):</span><br><span class="line">    &lt;code_to_be_profiled&gt;</span><br></pre></td></tr></table></figure>
<h2 id="NumPy"><a href="#NumPy" class="headerlink" title="NumPy"></a>NumPy</h2><p><strong>Array manipulation mini language. Can run up to one hundred times faster than equivalent Python code.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install numpy</span></span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;array&gt; = np.array(&lt;list&gt;)</span><br><span class="line">&lt;array&gt; = np.arange(from_inclusive, to_exclusive, ±step_size)</span><br><span class="line">&lt;array&gt; = np.ones(&lt;shape&gt;)</span><br><span class="line">&lt;array&gt; = np.random.randint(from_inclusive, to_exclusive, &lt;shape&gt;)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;array&gt;.shape = &lt;shape&gt;</span><br><span class="line">&lt;view&gt;  = &lt;array&gt;.reshape(&lt;shape&gt;)</span><br><span class="line">&lt;view&gt;  = np.broadcast_to(&lt;array&gt;, &lt;shape&gt;)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;array&gt; = &lt;array&gt;.sum(axis)</span><br><span class="line">indexes = &lt;array&gt;.argmin(axis)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Shape is a tuple of dimension sizes.</strong></li>
<li><strong>Axis is an index of dimension that gets collapsed. Leftmost dimension has index 0.</strong></li>
</ul>
<h3 id="Indexing"><a href="#Indexing" class="headerlink" title="Indexing"></a>Indexing</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;el&gt;       = &lt;2d_array&gt;[0, 0]        <span class="comment"># First element.</span></span><br><span class="line">&lt;1d_view&gt;  = &lt;2d_array&gt;[0]           <span class="comment"># First row.</span></span><br><span class="line">&lt;1d_view&gt;  = &lt;2d_array&gt;[:, 0]        <span class="comment"># First column. Also [..., 0].</span></span><br><span class="line">&lt;3d_view&gt;  = &lt;2d_array&gt;[None, :, :]  <span class="comment"># Expanded by dimension of size 1.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;1d_array&gt; = &lt;2d_array&gt;[&lt;1d_row_indexes&gt;, &lt;1d_column_indexes&gt;]</span><br><span class="line">&lt;2d_array&gt; = &lt;2d_array&gt;[&lt;2d_row_indexes&gt;, &lt;2d_column_indexes&gt;]</span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;2d_bools&gt; = &lt;2d_array&gt; &gt; 0</span><br><span class="line">&lt;1d_array&gt; = &lt;2d_array&gt;[&lt;2d_bools&gt;]</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>If row and column indexes differ in shape, they are combined with broadcasting.</strong></li>
</ul>
<h3 id="Broadcasting"><a href="#Broadcasting" class="headerlink" title="Broadcasting"></a>Broadcasting</h3><p><strong>Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">left  = [[<span class="number">0.1</span>], [<span class="number">0.6</span>], [<span class="number">0.8</span>]]        <span class="comment"># Shape: (3, 1)</span></span><br><span class="line">right = [ <span class="number">0.1</span> ,  <span class="number">0.6</span> ,  <span class="number">0.8</span> ]        <span class="comment"># Shape: (3)</span></span><br></pre></td></tr></table></figure>
<h4 id="1-If-array-shapes-differ-in-length-left-pad-the-shorter-shape-with-ones"><a href="#1-If-array-shapes-differ-in-length-left-pad-the-shorter-shape-with-ones" class="headerlink" title="1. If array shapes differ in length, left-pad the shorter shape with ones:"></a>1. If array shapes differ in length, left-pad the shorter shape with ones:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">left  = [[<span class="number">0.1</span>], [<span class="number">0.6</span>], [<span class="number">0.8</span>]]        <span class="comment"># Shape: (3, 1)</span></span><br><span class="line">right = [[<span class="number">0.1</span> ,  <span class="number">0.6</span> ,  <span class="number">0.8</span>]]        <span class="comment"># Shape: (1, 3) &lt;- !</span></span><br></pre></td></tr></table></figure>
<h4 id="2-If-any-dimensions-differ-in-size-expand-the-ones-that-have-size-1-by-duplicating-their-elements"><a href="#2-If-any-dimensions-differ-in-size-expand-the-ones-that-have-size-1-by-duplicating-their-elements" class="headerlink" title="2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:"></a>2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">left  = [[<span class="number">0.1</span>, <span class="number">0.1</span>, <span class="number">0.1</span>], [<span class="number">0.6</span>, <span class="number">0.6</span>, <span class="number">0.6</span>], [<span class="number">0.8</span>, <span class="number">0.8</span>, <span class="number">0.8</span>]]  <span class="comment"># Shape: (3, 3) &lt;- !</span></span><br><span class="line">right = [[<span class="number">0.1</span>, <span class="number">0.6</span>, <span class="number">0.8</span>], [<span class="number">0.1</span>, <span class="number">0.6</span>, <span class="number">0.8</span>], [<span class="number">0.1</span>, <span class="number">0.6</span>, <span class="number">0.8</span>]]  <span class="comment"># Shape: (3, 3) &lt;- !</span></span><br></pre></td></tr></table></figure>
<h4 id="3-If-neither-non-matching-dimension-has-size-1-rise-an-error"><a href="#3-If-neither-non-matching-dimension-has-size-1-rise-an-error" class="headerlink" title="3. If neither non-matching dimension has size 1, rise an error."></a>3. If neither non-matching dimension has size 1, rise an error.</h4><h3 id="Example-2"><a href="#Example-2" class="headerlink" title="Example"></a>Example</h3><h4 id="For-each-point-returns-index-of-its-nearest-point-0-1-0-6-0-8-gt-1-2-1"><a href="#For-each-point-returns-index-of-its-nearest-point-0-1-0-6-0-8-gt-1-2-1" class="headerlink" title="For each point returns index of its nearest point ([0.1, 0.6, 0.8] =&gt; [1, 2, 1]):"></a>For each point returns index of its nearest point (<code>[0.1, 0.6, 0.8] =&gt; [1, 2, 1]</code>):</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>points = np.array([<span class="number">0.1</span>, <span class="number">0.6</span>, <span class="number">0.8</span>])</span><br><span class="line">[ <span class="number">0.1</span>,  <span class="number">0.6</span>,  <span class="number">0.8</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>wrapped_points = points.reshape(<span class="number">3</span>, <span class="number">1</span>)</span><br><span class="line">[[ <span class="number">0.1</span>],</span><br><span class="line"> [ <span class="number">0.6</span>],</span><br><span class="line"> [ <span class="number">0.8</span>]]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>distances = wrapped_points - points</span><br><span class="line">[[ <span class="number">0.</span> , <span class="number">-0.5</span>, <span class="number">-0.7</span>],</span><br><span class="line"> [ <span class="number">0.5</span>,  <span class="number">0.</span> , <span class="number">-0.2</span>],</span><br><span class="line"> [ <span class="number">0.7</span>,  <span class="number">0.2</span>,  <span class="number">0.</span> ]]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>distances = np.abs(distances)</span><br><span class="line">[[ <span class="number">0.</span> ,  <span class="number">0.5</span>,  <span class="number">0.7</span>],</span><br><span class="line"> [ <span class="number">0.5</span>,  <span class="number">0.</span> ,  <span class="number">0.2</span>],</span><br><span class="line"> [ <span class="number">0.7</span>,  <span class="number">0.2</span>,  <span class="number">0.</span> ]]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>i = np.arange(<span class="number">3</span>)</span><br><span class="line">[<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>distances[i, i] = np.inf</span><br><span class="line">[[ inf,  <span class="number">0.5</span>,  <span class="number">0.7</span>],</span><br><span class="line"> [ <span class="number">0.5</span>,  inf,  <span class="number">0.2</span>],</span><br><span class="line"> [ <span class="number">0.7</span>,  <span class="number">0.2</span>,  inf]]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>distances.argmin(<span class="number">1</span>)</span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">1</span>]</span><br></pre></td></tr></table></figure>
<h2 id="Image"><a href="#Image" class="headerlink" title="Image"></a>Image</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install pillow</span></span><br><span class="line"><span class="keyword">from</span> PIL <span class="keyword">import</span> Image</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;Image&gt; = Image.new(<span class="string">'&lt;mode&gt;'</span>, (width, height))</span><br><span class="line">&lt;Image&gt; = Image.open(<span class="string">'&lt;path&gt;'</span>)</span><br><span class="line">&lt;Image&gt; = &lt;Image&gt;.convert(<span class="string">'&lt;mode&gt;'</span>)</span><br><span class="line">&lt;Image&gt;.save(<span class="string">'&lt;path&gt;'</span>)</span><br><span class="line">&lt;Image&gt;.show()</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;tuple/int&gt; = &lt;Image&gt;.getpixel((x, y))          <span class="comment"># Returns a pixel.</span></span><br><span class="line">&lt;Image&gt;.putpixel((x, y), &lt;tuple/int&gt;)           <span class="comment"># Writes a pixel to image.</span></span><br><span class="line">&lt;ImagingCore&gt; = &lt;Image&gt;.getdata()               <span class="comment"># Returns a sequence of pixels.</span></span><br><span class="line">&lt;Image&gt;.putdata(&lt;list/ImagingCore&gt;)             <span class="comment"># Writes a sequence of pixels.</span></span><br><span class="line">&lt;Image&gt;.paste(&lt;Image&gt;, (x, y))                  <span class="comment"># Writes an image to image.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;2d_array&gt; = np.array(&lt;Image&gt;)                  <span class="comment"># NumPy array from greyscale image.</span></span><br><span class="line">&lt;3d_array&gt; = np.array(&lt;Image&gt;)                  <span class="comment"># NumPy array from color image.</span></span><br><span class="line">&lt;Image&gt;    = Image.fromarray(&lt;array&gt;)           <span class="comment"># Image from NumPy array.</span></span><br></pre></td></tr></table></figure>
<h3 id="Modes-1"><a href="#Modes-1" class="headerlink" title="Modes"></a>Modes</h3><ul>
<li><strong><code>&#39;1&#39;</code> - 1-bit pixels, black and white, stored with one pixel per byte.</strong></li>
<li><strong><code>&#39;L&#39;</code> - 8-bit pixels, greyscale.</strong></li>
<li><strong><code>&#39;RGB&#39;</code> - 3x8-bit pixels, true color.</strong></li>
<li><strong><code>&#39;RGBA&#39;</code> - 4x8-bit pixels, true color with transparency mask.</strong></li>
<li><strong><code>&#39;HSV&#39;</code> - 3x8-bit pixels, Hue, Saturation, Value color space.</strong></li>
</ul>
<h3 id="Examples"><a href="#Examples" class="headerlink" title="Examples"></a>Examples</h3><h4 id="Creates-a-PNG-image-of-a-rainbow-gradient"><a href="#Creates-a-PNG-image-of-a-rainbow-gradient" class="headerlink" title="Creates a PNG image of a rainbow gradient:"></a>Creates a PNG image of a rainbow gradient:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">WIDTH, HEIGHT = <span class="number">100</span>, <span class="number">100</span></span><br><span class="line">size = WIDTH * HEIGHT</span><br><span class="line">hues = [<span class="number">255</span> * i/size <span class="keyword">for</span> i <span class="keyword">in</span> range(size)]</span><br><span class="line">img = Image.new(<span class="string">'HSV'</span>, (WIDTH, HEIGHT))</span><br><span class="line">img.putdata([(int(h), <span class="number">255</span>, <span class="number">255</span>) <span class="keyword">for</span> h <span class="keyword">in</span> hues])</span><br><span class="line">img.convert(<span class="string">'RGB'</span>).save(<span class="string">'test.png'</span>)</span><br></pre></td></tr></table></figure>
<h4 id="Adds-noise-to-a-PNG-image"><a href="#Adds-noise-to-a-PNG-image" class="headerlink" title="Adds noise to a PNG image:"></a>Adds noise to a PNG image:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> random <span class="keyword">import</span> randint</span><br><span class="line">add_noise = <span class="keyword">lambda</span> value: max(<span class="number">0</span>, min(<span class="number">255</span>, value + randint(<span class="number">-20</span>, <span class="number">20</span>)))</span><br><span class="line">img = Image.open(<span class="string">'test.png'</span>).convert(<span class="string">'HSV'</span>)</span><br><span class="line">img.putdata([(add_noise(h), s, v) <span class="keyword">for</span> h, s, v <span class="keyword">in</span> img.getdata()])</span><br><span class="line">img.convert(<span class="string">'RGB'</span>).save(<span class="string">'test.png'</span>)</span><br></pre></td></tr></table></figure>
<h3 id="Drawing"><a href="#Drawing" class="headerlink" title="Drawing"></a>Drawing</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> PIL <span class="keyword">import</span> ImageDraw</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;ImageDraw&gt; = ImageDraw.Draw(&lt;Image&gt;)</span><br><span class="line">&lt;ImageDraw&gt;.point((x, y), fill=<span class="literal">None</span>)</span><br><span class="line">&lt;ImageDraw&gt;.line((x1, y1, x2, y2 [, ...]), fill=<span class="literal">None</span>, width=<span class="number">0</span>, joint=<span class="literal">None</span>) </span><br><span class="line">&lt;ImageDraw&gt;.arc((x1, y1, x2, y2), from_deg, to_deg, fill=<span class="literal">None</span>, width=<span class="number">0</span>)</span><br><span class="line">&lt;ImageDraw&gt;.rectangle((x1, y1, x2, y2), fill=<span class="literal">None</span>, outline=<span class="literal">None</span>, width=<span class="number">0</span>)</span><br><span class="line">&lt;ImageDraw&gt;.polygon((x1, y1, x2, y2 [, ...]), fill=<span class="literal">None</span>, outline=<span class="literal">None</span>)</span><br><span class="line">&lt;ImageDraw&gt;.ellipse((x1, y1, x2, y2), fill=<span class="literal">None</span>, outline=<span class="literal">None</span>, width=<span class="number">0</span>)</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Use <code>&#39;fill=&lt;color&gt;&#39;</code> to set the primary color.</strong></li>
<li><strong>Use <code>&#39;outline=&lt;color&gt;&#39;</code> to set the secondary color.</strong></li>
<li><strong>Color can be specified as a tuple, int, <code>&#39;#rrggbb&#39;</code> string or a color name.</strong></li>
</ul>
<h2 id="Animation"><a href="#Animation" class="headerlink" title="Animation"></a>Animation</h2><h4 id="Creates-a-GIF-of-a-bouncing-ball"><a href="#Creates-a-GIF-of-a-bouncing-ball" class="headerlink" title="Creates a GIF of a bouncing ball:"></a>Creates a GIF of a bouncing ball:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install pillow imageio</span></span><br><span class="line"><span class="keyword">from</span> PIL <span class="keyword">import</span> Image, ImageDraw</span><br><span class="line"><span class="keyword">import</span> imageio</span><br><span class="line">WIDTH, R = <span class="number">126</span>, <span class="number">10</span></span><br><span class="line">frames = []</span><br><span class="line"><span class="keyword">for</span> velocity <span class="keyword">in</span> range(<span class="number">15</span>):</span><br><span class="line">    y = sum(range(velocity+<span class="number">1</span>))</span><br><span class="line">    frame = Image.new(<span class="string">'L'</span>, (WIDTH, WIDTH))</span><br><span class="line">    draw  = ImageDraw.Draw(frame)</span><br><span class="line">    draw.ellipse((WIDTH/<span class="number">2</span>-R, y, WIDTH/<span class="number">2</span>+R, y+<span class="number">2</span>*R), fill=<span class="string">'white'</span>)</span><br><span class="line">    frames.append(frame)</span><br><span class="line">frames += reversed(frames[<span class="number">1</span>:<span class="number">-1</span>])</span><br><span class="line">imageio.mimsave(<span class="string">'test.gif'</span>, frames, duration=<span class="number">0.03</span>)</span><br></pre></td></tr></table></figure>
<h2 id="Audio"><a href="#Audio" class="headerlink" title="Audio"></a>Audio</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> wave</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;Wave_read&gt;  = wave.open(<span class="string">'&lt;path&gt;'</span>, <span class="string">'rb'</span>)</span><br><span class="line">framerate    = &lt;Wave_read&gt;.getframerate()       <span class="comment"># Number of frames per second.</span></span><br><span class="line">nchannels    = &lt;Wave_read&gt;.getnchannels()       <span class="comment"># Number of samples per frame.</span></span><br><span class="line">sampwidth    = &lt;Wave_read&gt;.getsampwidth()       <span class="comment"># Sample size in bytes.</span></span><br><span class="line">nframes      = &lt;Wave_read&gt;.getnframes()         <span class="comment"># Number of frames.</span></span><br><span class="line">&lt;params&gt;     = &lt;Wave_read&gt;.getparams()          <span class="comment"># Immutable collection of above.</span></span><br><span class="line">&lt;bytes&gt;      = &lt;Wave_read&gt;.readframes(nframes)  <span class="comment"># Returns next 'nframes' frames.</span></span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;Wave_write&gt; = wave.open(<span class="string">'&lt;path&gt;'</span>, <span class="string">'wb'</span>)</span><br><span class="line">&lt;Wave_write&gt;.setframerate(&lt;int&gt;)                <span class="comment"># 44100 for CD, 48000 for video.</span></span><br><span class="line">&lt;Wave_write&gt;.setnchannels(&lt;int&gt;)                <span class="comment"># 1 for mono, 2 for stereo.</span></span><br><span class="line">&lt;Wave_write&gt;.setsampwidth(&lt;int&gt;)                <span class="comment"># 2 for CD quality sound.</span></span><br><span class="line">&lt;Wave_write&gt;.setparams(&lt;params&gt;)                <span class="comment"># Sets all parameters.</span></span><br><span class="line">&lt;Wave_write&gt;.writeframes(&lt;bytes&gt;)               <span class="comment"># Appends frames to file.</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Bytes object contains a sequence of frames, each consisting of one or more samples.</strong></li>
<li><strong>In stereo signal first sample of a frame belongs to the left channel.</strong></li>
<li><strong>Each sample consists of one or more bytes that, when converted to an integer, indicate the displacement of a speaker membrane at a given moment.</strong></li>
<li><strong>If sample width is one, then the integer should be encoded unsigned.</strong></li>
<li><strong>For all other sizes the integer should be encoded signed with little-endian byte order.</strong></li>
</ul>
<h3 id="Sample-Values"><a href="#Sample-Values" class="headerlink" title="Sample Values"></a>Sample Values</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">+-----------+-------------+------+-------------+</span><br><span class="line">| sampwidth |     min     | zero |     max     |</span><br><span class="line">+-----------+-------------+------+-------------+</span><br><span class="line">|     1     |           0 |  128 |         255 |</span><br><span class="line">|     2     |      -32768 |    0 |       32767 |</span><br><span class="line">|     3     |    -8388608 |    0 |     8388607 |</span><br><span class="line">|     4     | -2147483648 |    0 |  2147483647 |</span><br><span class="line">+-----------+-------------+------+-------------+</span><br></pre></td></tr></table></figure>
<h3 id="Read-Float-Samples-from-WAV-File"><a href="#Read-Float-Samples-from-WAV-File" class="headerlink" title="Read Float Samples from WAV File"></a>Read Float Samples from WAV File</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">read_wav_file</span><span class="params">(filename)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_int</span><span class="params">(a_bytes)</span>:</span></span><br><span class="line">        an_int = int.from_bytes(a_bytes, <span class="string">'little'</span>, signed=width!=<span class="number">1</span>)</span><br><span class="line">        <span class="keyword">return</span> an_int - <span class="number">128</span> * (width == <span class="number">1</span>)</span><br><span class="line">    <span class="keyword">with</span> wave.open(filename, <span class="string">'rb'</span>) <span class="keyword">as</span> file:</span><br><span class="line">        width  = file.getsampwidth()</span><br><span class="line">        frames = file.readframes(file.getnframes())</span><br><span class="line">    byte_samples = (frames[i: i + width] <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">0</span>, len(frames), width))</span><br><span class="line">    <span class="keyword">return</span> [get_int(b) / pow(<span class="number">2</span>, width * <span class="number">8</span> - <span class="number">1</span>) <span class="keyword">for</span> b <span class="keyword">in</span> byte_samples]</span><br></pre></td></tr></table></figure>
<h3 id="Write-Float-Samples-to-WAV-File"><a href="#Write-Float-Samples-to-WAV-File" class="headerlink" title="Write Float Samples to WAV File"></a>Write Float Samples to WAV File</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">write_to_wav_file</span><span class="params">(filename, float_samples, nchannels=<span class="number">1</span>, sampwidth=<span class="number">2</span>, framerate=<span class="number">44100</span>)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_bytes</span><span class="params">(a_float)</span>:</span></span><br><span class="line">        a_float = max(<span class="number">-1</span>, min(<span class="number">1</span> - <span class="number">2e-16</span>, a_float))</span><br><span class="line">        a_float += sampwidth == <span class="number">1</span></span><br><span class="line">        a_float *= pow(<span class="number">2</span>, sampwidth * <span class="number">8</span> - <span class="number">1</span>)</span><br><span class="line">        <span class="keyword">return</span> int(a_float).to_bytes(sampwidth, <span class="string">'little'</span>, signed=sampwidth!=<span class="number">1</span>) </span><br><span class="line">    <span class="keyword">with</span> wave.open(filename, <span class="string">'wb'</span>) <span class="keyword">as</span> file:</span><br><span class="line">        file.setnchannels(nchannels)</span><br><span class="line">        file.setsampwidth(sampwidth)</span><br><span class="line">        file.setframerate(framerate)</span><br><span class="line">        file.writeframes(<span class="string">b''</span>.join(get_bytes(f) <span class="keyword">for</span> f <span class="keyword">in</span> float_samples))</span><br></pre></td></tr></table></figure>
<h3 id="Examples-1"><a href="#Examples-1" class="headerlink" title="Examples"></a>Examples</h3><h4 id="Saves-a-sine-wave-to-a-mono-WAV-file"><a href="#Saves-a-sine-wave-to-a-mono-WAV-file" class="headerlink" title="Saves a sine wave to a mono WAV file:"></a>Saves a sine wave to a mono WAV file:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> math <span class="keyword">import</span> pi, sin</span><br><span class="line">samples_f = (sin(i * <span class="number">2</span> * pi * <span class="number">440</span> / <span class="number">44100</span>) <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">100000</span>))</span><br><span class="line">write_to_wav_file(<span class="string">'test.wav'</span>, samples_f)</span><br></pre></td></tr></table></figure>
<h4 id="Adds-noise-to-a-mono-WAV-file"><a href="#Adds-noise-to-a-mono-WAV-file" class="headerlink" title="Adds noise to a mono WAV file:"></a>Adds noise to a mono WAV file:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> random <span class="keyword">import</span> random</span><br><span class="line">add_noise = <span class="keyword">lambda</span> value: value + (random() - <span class="number">0.5</span>) * <span class="number">0.03</span></span><br><span class="line">samples_f = (add_noise(f) <span class="keyword">for</span> f <span class="keyword">in</span> read_wav_file(<span class="string">'test.wav'</span>))</span><br><span class="line">write_to_wav_file(<span class="string">'test.wav'</span>, samples_f)</span><br></pre></td></tr></table></figure>
<h4 id="Plays-a-WAV-file"><a href="#Plays-a-WAV-file" class="headerlink" title="Plays a WAV file:"></a>Plays a WAV file:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install simpleaudio</span></span><br><span class="line"><span class="keyword">import</span> simpleaudio</span><br><span class="line"><span class="keyword">with</span> wave.open(<span class="string">'test.wav'</span>, <span class="string">'rb'</span>) <span class="keyword">as</span> file:</span><br><span class="line">    p = file.getparams()</span><br><span class="line">    frames = file.readframes(p.nframes)</span><br><span class="line">    simpleaudio.play_buffer(frames, p.nchannels, p.sampwidth, p.framerate)</span><br></pre></td></tr></table></figure>
<h3 id="Text-to-Speech"><a href="#Text-to-Speech" class="headerlink" title="Text to Speech"></a>Text to Speech</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install pyttsx3</span></span><br><span class="line"><span class="keyword">import</span> pyttsx3</span><br><span class="line">engine = pyttsx3.init()</span><br><span class="line">engine.say(<span class="string">'Sally sells seashells by the seashore.'</span>)</span><br><span class="line">engine.runAndWait()</span><br></pre></td></tr></table></figure>
<h2 id="Synthesizer"><a href="#Synthesizer" class="headerlink" title="Synthesizer"></a>Synthesizer</h2><h4 id="Plays-Popcorn-by-Gershon-Kingsley"><a href="#Plays-Popcorn-by-Gershon-Kingsley" class="headerlink" title="Plays Popcorn by Gershon Kingsley:"></a>Plays Popcorn by Gershon Kingsley:</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># $ pip3 install simpleaudio</span></span><br><span class="line"><span class="keyword">import</span> simpleaudio, math, struct</span><br><span class="line"><span class="keyword">from</span> itertools <span class="keyword">import</span> chain, repeat</span><br><span class="line">F  = <span class="number">44100</span></span><br><span class="line">P1 = <span class="string">'71♪,69,,71♪,66,,62♪,66,,59♪,,,'</span></span><br><span class="line">P2 = <span class="string">'71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,'</span></span><br><span class="line">get_pause   = <span class="keyword">lambda</span> seconds: repeat(<span class="number">0</span>, int(seconds * F))</span><br><span class="line">sin_f       = <span class="keyword">lambda</span> i, hz: math.sin(i * <span class="number">2</span> * math.pi * hz / F)</span><br><span class="line">get_wave    = <span class="keyword">lambda</span> hz, seconds: (sin_f(i, hz) <span class="keyword">for</span> i <span class="keyword">in</span> range(int(seconds * F)))</span><br><span class="line">get_hz      = <span class="keyword">lambda</span> key: <span class="number">8.176</span> * <span class="number">2</span> ** (int(key) / <span class="number">12</span>)</span><br><span class="line">parse_note  = <span class="keyword">lambda</span> note: (get_hz(note[:<span class="number">2</span>]), <span class="number">0.25</span> <span class="keyword">if</span> <span class="string">'♪'</span> <span class="keyword">in</span> note <span class="keyword">else</span> <span class="number">0.125</span>)</span><br><span class="line">get_samples = <span class="keyword">lambda</span> note: get_wave(*parse_note(note)) <span class="keyword">if</span> note <span class="keyword">else</span> get_pause(<span class="number">0.125</span>)</span><br><span class="line">samples_f   = chain.from_iterable(get_samples(n) <span class="keyword">for</span> n <span class="keyword">in</span> <span class="string">f'<span class="subst">&#123;P1&#125;</span><span class="subst">&#123;P1&#125;</span><span class="subst">&#123;P2&#125;</span>'</span>.split(<span class="string">','</span>))</span><br><span class="line">samples_b   = <span class="string">b''</span>.join(struct.pack(<span class="string">'&lt;h'</span>, int(f * <span class="number">30000</span>)) <span class="keyword">for</span> f <span class="keyword">in</span> samples_f)</span><br><span class="line">simpleaudio.play_buffer(samples_b, <span class="number">1</span>, <span class="number">2</span>, F)</span><br></pre></td></tr></table></figure>
<h2 id="Basic-Script-Template"><a href="#Basic-Script-Template" class="headerlink" title="Basic Script Template"></a>Basic Script Template</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/env python3</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"><span class="comment"># Usage: .py</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> collections <span class="keyword">import</span> namedtuple</span><br><span class="line"><span class="keyword">from</span> dataclasses <span class="keyword">import</span> make_dataclass</span><br><span class="line"><span class="keyword">from</span> enum <span class="keyword">import</span> Enum</span><br><span class="line"><span class="keyword">from</span> sys <span class="keyword">import</span> argv</span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">###</span></span><br><span class="line"><span class="comment">##  UTIL</span></span><br><span class="line"><span class="comment">#</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">read_file</span><span class="params">(filename)</span>:</span></span><br><span class="line">    <span class="keyword">with</span> open(filename, encoding=<span class="string">'utf-8'</span>) <span class="keyword">as</span> file:</span><br><span class="line">        <span class="keyword">return</span> file.readlines()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/python/" rel="tag"># python</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/12/30/GoldenEye-wp/" rel="next" title="GoldenEye_wp">
                <i class="fa fa-chevron-left"></i> GoldenEye_wp
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/01/14/m0n0防火墙基础配置/" rel="prev" title="m0n0防火墙基础配置">
                m0n0防火墙基础配置 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/pikachu.jpg" alt="srat1999">
            
              <p class="site-author-name" itemprop="name">srat1999</p>
              <p class="site-description motion-element" itemprop="description">the higher you stand the more you can see</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">55</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">30</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/srat1999" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:srat1999@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Comprehensive-Python-Cheatsheet"><span class="nav-number">1.</span> <span class="nav-text">Comprehensive Python Cheatsheet</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#来自github"><span class="nav-number">1.1.</span> <span class="nav-text">来自github</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Contents"><span class="nav-number">1.2.</span> <span class="nav-text">Contents</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Main"><span class="nav-number">1.3.</span> <span class="nav-text">Main</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#List"><span class="nav-number">1.4.</span> <span class="nav-text">List</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Dictionary"><span class="nav-number">1.5.</span> <span class="nav-text">Dictionary</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Counter"><span class="nav-number">1.5.1.</span> <span class="nav-text">Counter</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Set"><span class="nav-number">1.6.</span> <span class="nav-text">Set</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Frozen-Set"><span class="nav-number">1.6.1.</span> <span class="nav-text">Frozen Set</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Tuple"><span class="nav-number">1.7.</span> <span class="nav-text">Tuple</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Named-Tuple"><span class="nav-number">1.7.1.</span> <span class="nav-text">Named Tuple</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Range"><span class="nav-number">1.8.</span> <span class="nav-text">Range</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Enumerate"><span class="nav-number">1.9.</span> <span class="nav-text">Enumerate</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Iterator"><span class="nav-number">1.10.</span> <span class="nav-text">Iterator</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Itertools"><span class="nav-number">1.10.1.</span> <span class="nav-text">Itertools</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Generator"><span class="nav-number">1.11.</span> <span class="nav-text">Generator</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Type"><span class="nav-number">1.12.</span> <span class="nav-text">Type</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Some-types-do-not-have-built-in-names-so-they-must-be-imported"><span class="nav-number">1.12.0.1.</span> <span class="nav-text">Some types do not have built-in names, so they must be imported:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ABC"><span class="nav-number">1.12.1.</span> <span class="nav-text">ABC</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#String"><span class="nav-number">1.13.</span> <span class="nav-text">String</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Property-Methods"><span class="nav-number">1.13.1.</span> <span class="nav-text">Property Methods</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Regex"><span class="nav-number">1.14.</span> <span class="nav-text">Regex</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Match-Object"><span class="nav-number">1.14.1.</span> <span class="nav-text">Match Object</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Special-Sequences"><span class="nav-number">1.14.2.</span> <span class="nav-text">Special Sequences</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Format"><span class="nav-number">1.15.</span> <span class="nav-text">Format</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Attributes"><span class="nav-number">1.15.1.</span> <span class="nav-text">Attributes</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#General-Options"><span class="nav-number">1.15.2.</span> <span class="nav-text">General Options</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Strings"><span class="nav-number">1.15.3.</span> <span class="nav-text">Strings</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Numbers"><span class="nav-number">1.15.4.</span> <span class="nav-text">Numbers</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Floats"><span class="nav-number">1.15.5.</span> <span class="nav-text">Floats</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Comparison-of-float-presentation-types"><span class="nav-number">1.15.5.1.</span> <span class="nav-text">Comparison of float presentation types:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Ints"><span class="nav-number">1.15.6.</span> <span class="nav-text">Ints</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Numbers-1"><span class="nav-number">1.16.</span> <span class="nav-text">Numbers</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Types"><span class="nav-number">1.16.1.</span> <span class="nav-text">Types</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Basic-Functions"><span class="nav-number">1.16.2.</span> <span class="nav-text">Basic Functions</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Math"><span class="nav-number">1.16.3.</span> <span class="nav-text">Math</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Statistics"><span class="nav-number">1.16.4.</span> <span class="nav-text">Statistics</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Random"><span class="nav-number">1.16.5.</span> <span class="nav-text">Random</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Bin-Hex"><span class="nav-number">1.16.6.</span> <span class="nav-text">Bin, Hex</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Bitwise-Operators"><span class="nav-number">1.16.7.</span> <span class="nav-text">Bitwise Operators</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Combinatorics"><span class="nav-number">1.17.</span> <span class="nav-text">Combinatorics</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Datetime"><span class="nav-number">1.18.</span> <span class="nav-text">Datetime</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Constructors"><span class="nav-number">1.18.1.</span> <span class="nav-text">Constructors</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Now"><span class="nav-number">1.18.2.</span> <span class="nav-text">Now</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Timezone"><span class="nav-number">1.18.3.</span> <span class="nav-text">Timezone</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Encode"><span class="nav-number">1.18.4.</span> <span class="nav-text">Encode</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Decode"><span class="nav-number">1.18.5.</span> <span class="nav-text">Decode</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Format-1"><span class="nav-number">1.18.6.</span> <span class="nav-text">Format</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Arithmetics"><span class="nav-number">1.18.7.</span> <span class="nav-text">Arithmetics</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Arguments"><span class="nav-number">1.19.</span> <span class="nav-text">Arguments</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Inside-Function-Call"><span class="nav-number">1.19.1.</span> <span class="nav-text">Inside Function Call</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Inside-Function-Definition"><span class="nav-number">1.19.2.</span> <span class="nav-text">Inside Function Definition</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Splat-Operator"><span class="nav-number">1.20.</span> <span class="nav-text">Splat Operator</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Inside-Function-Call-1"><span class="nav-number">1.20.1.</span> <span class="nav-text">Inside Function Call</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Is-the-same-as"><span class="nav-number">1.20.1.1.</span> <span class="nav-text">Is the same as:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Inside-Function-Definition-1"><span class="nav-number">1.20.2.</span> <span class="nav-text">Inside Function Definition</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Legal-argument-combinations"><span class="nav-number">1.20.2.1.</span> <span class="nav-text">Legal argument combinations:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Other-Uses"><span class="nav-number">1.20.3.</span> <span class="nav-text">Other Uses</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Inline"><span class="nav-number">1.21.</span> <span class="nav-text">Inline</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Lambda"><span class="nav-number">1.21.1.</span> <span class="nav-text">Lambda</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Comprehension"><span class="nav-number">1.21.2.</span> <span class="nav-text">Comprehension</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Is-the-same-as-1"><span class="nav-number">1.21.2.1.</span> <span class="nav-text">Is the same as:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Map-Filter-Reduce"><span class="nav-number">1.21.3.</span> <span class="nav-text">Map, Filter, Reduce</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Any-All"><span class="nav-number">1.21.4.</span> <span class="nav-text">Any, All</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#If-Else"><span class="nav-number">1.21.5.</span> <span class="nav-text">If - Else</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Namedtuple-Enum-Dataclass"><span class="nav-number">1.21.6.</span> <span class="nav-text">Namedtuple, Enum, Dataclass</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Closure"><span class="nav-number">1.22.</span> <span class="nav-text">Closure</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Partial"><span class="nav-number">1.22.1.</span> <span class="nav-text">Partial</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Nonlocal"><span class="nav-number">1.22.2.</span> <span class="nav-text">Nonlocal</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Decorator"><span class="nav-number">1.23.</span> <span class="nav-text">Decorator</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Debugger-Example"><span class="nav-number">1.23.1.</span> <span class="nav-text">Debugger Example</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#LRU-Cache"><span class="nav-number">1.23.2.</span> <span class="nav-text">LRU Cache</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Parametrized-Decorator"><span class="nav-number">1.23.3.</span> <span class="nav-text">Parametrized Decorator</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Class"><span class="nav-number">1.24.</span> <span class="nav-text">Class</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Str-use-cases"><span class="nav-number">1.24.0.1.</span> <span class="nav-text">Str() use cases:</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Repr-use-cases"><span class="nav-number">1.24.0.2.</span> <span class="nav-text">Repr() use cases:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Constructor-Overloading"><span class="nav-number">1.24.1.</span> <span class="nav-text">Constructor Overloading</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Inheritance"><span class="nav-number">1.24.2.</span> <span class="nav-text">Inheritance</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Multiple-Inheritance"><span class="nav-number">1.24.3.</span> <span class="nav-text">Multiple Inheritance</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Property"><span class="nav-number">1.24.4.</span> <span class="nav-text">Property</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Dataclass"><span class="nav-number">1.24.5.</span> <span class="nav-text">Dataclass</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Inline-1"><span class="nav-number">1.24.5.1.</span> <span class="nav-text">Inline:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Slots"><span class="nav-number">1.24.6.</span> <span class="nav-text">Slots</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Copy"><span class="nav-number">1.24.7.</span> <span class="nav-text">Copy</span></a></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#Duck-Types"><span class="nav-number">1.25.</span> <span class="nav-text">Duck Types</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Comparable"><span class="nav-number">1.25.1.</span> <span class="nav-text">Comparable</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Hashable"><span class="nav-number">1.25.2.</span> <span class="nav-text">Hashable</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Sortable"><span class="nav-number">1.25.3.</span> <span class="nav-text">Sortable</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Iterator-1"><span class="nav-number">1.25.4.</span> <span class="nav-text">Iterator</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Python-has-many-different-iterator-objects"><span class="nav-number">1.25.4.1.</span> <span class="nav-text">Python has many different iterator objects:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Callable"><span class="nav-number">1.25.5.</span> <span class="nav-text">Callable</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Context-Manager"><span class="nav-number">1.25.6.</span> <span class="nav-text">Context Manager</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Iterable-Duck-Types"><span class="nav-number">1.26.</span> <span class="nav-text">Iterable Duck Types</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Iterable"><span class="nav-number">1.26.1.</span> <span class="nav-text">Iterable</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Collection"><span class="nav-number">1.26.2.</span> <span class="nav-text">Collection</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Sequence"><span class="nav-number">1.26.3.</span> <span class="nav-text">Sequence</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Collections-abc-Sequence"><span class="nav-number">1.26.4.</span> <span class="nav-text">Collections.abc.Sequence</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Table-of-required-and-automatically-available-special-methods"><span class="nav-number">1.26.4.1.</span> <span class="nav-text">Table of required and automatically available special methods:</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Enum"><span class="nav-number">1.27.</span> <span class="nav-text">Enum</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Inline-2"><span class="nav-number">1.27.1.</span> <span class="nav-text">Inline</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Functions-can-not-be-values-so-they-must-be-wrapped"><span class="nav-number">1.27.1.1.</span> <span class="nav-text">Functions can not be values, so they must be wrapped:</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Exceptions"><span class="nav-number">1.28.</span> <span class="nav-text">Exceptions</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Basic-Example"><span class="nav-number">1.28.1.</span> <span class="nav-text">Basic Example</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Complex-Example"><span class="nav-number">1.28.2.</span> <span class="nav-text">Complex Example</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Catching-Exceptions"><span class="nav-number">1.28.3.</span> <span class="nav-text">Catching Exceptions</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Raising-Exceptions"><span class="nav-number">1.28.4.</span> <span class="nav-text">Raising Exceptions</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Re-raising-caught-exception"><span class="nav-number">1.28.4.1.</span> <span class="nav-text">Re-raising caught exception:</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Useful-built-in-exceptions"><span class="nav-number">1.28.4.2.</span> <span class="nav-text">Useful built-in exceptions:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Common-Built-in-Exceptions"><span class="nav-number">1.28.5.</span> <span class="nav-text">Common Built-in Exceptions</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Collections-and-their-exceptions"><span class="nav-number">1.28.5.1.</span> <span class="nav-text">Collections and their exceptions:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#User-defined-Exceptions"><span class="nav-number">1.28.6.</span> <span class="nav-text">User-defined Exceptions</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Print"><span class="nav-number">1.29.</span> <span class="nav-text">Print</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Pretty-Print"><span class="nav-number">1.29.1.</span> <span class="nav-text">Pretty Print</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Input"><span class="nav-number">1.30.</span> <span class="nav-text">Input</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Command-Line-Arguments"><span class="nav-number">1.31.</span> <span class="nav-text">Command Line Arguments</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Argparse"><span class="nav-number">1.31.1.</span> <span class="nav-text">Argparse</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Open"><span class="nav-number">1.32.</span> <span class="nav-text">Open</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Modes"><span class="nav-number">1.32.1.</span> <span class="nav-text">Modes</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Exceptions-1"><span class="nav-number">1.32.2.</span> <span class="nav-text">Exceptions</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#File-Object"><span class="nav-number">1.32.3.</span> <span class="nav-text">File Object</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Read-Text-from-File"><span class="nav-number">1.32.4.</span> <span class="nav-text">Read Text from File</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Write-Text-to-File"><span class="nav-number">1.32.5.</span> <span class="nav-text">Write Text to File</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Path"><span class="nav-number">1.33.</span> <span class="nav-text">Path</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#DirEntry"><span class="nav-number">1.33.1.</span> <span class="nav-text">DirEntry</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Path-Object"><span class="nav-number">1.33.2.</span> <span class="nav-text">Path Object</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#OS-Commands"><span class="nav-number">1.34.</span> <span class="nav-text">OS Commands</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Files-and-Directories"><span class="nav-number">1.34.1.</span> <span class="nav-text">Files and Directories</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Shell-Commands"><span class="nav-number">1.34.2.</span> <span class="nav-text">Shell Commands</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Using-subprocess"><span class="nav-number">1.34.2.1.</span> <span class="nav-text">Using subprocess:</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JSON"><span class="nav-number">1.35.</span> <span class="nav-text">JSON</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Read-Object-from-JSON-File"><span class="nav-number">1.35.1.</span> <span class="nav-text">Read Object from JSON File</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Write-Object-to-JSON-File"><span class="nav-number">1.35.2.</span> <span class="nav-text">Write Object to JSON File</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Pickle"><span class="nav-number">1.36.</span> <span class="nav-text">Pickle</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Read-Object-from-File"><span class="nav-number">1.36.1.</span> <span class="nav-text">Read Object from File</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Write-Object-to-File"><span class="nav-number">1.36.2.</span> <span class="nav-text">Write Object to File</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CSV"><span class="nav-number">1.37.</span> <span class="nav-text">CSV</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Read"><span class="nav-number">1.37.1.</span> <span class="nav-text">Read</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Write"><span class="nav-number">1.37.2.</span> <span class="nav-text">Write</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Parameters"><span class="nav-number">1.37.3.</span> <span class="nav-text">Parameters</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Dialects"><span class="nav-number">1.37.4.</span> <span class="nav-text">Dialects</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Read-Rows-from-CSV-File"><span class="nav-number">1.37.5.</span> <span class="nav-text">Read Rows from CSV File</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Write-Rows-to-CSV-File"><span class="nav-number">1.37.6.</span> <span class="nav-text">Write Rows to CSV File</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SQLite"><span class="nav-number">1.38.</span> <span class="nav-text">SQLite</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Connect"><span class="nav-number">1.38.1.</span> <span class="nav-text">Connect</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Read-1"><span class="nav-number">1.38.2.</span> <span class="nav-text">Read</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Write-1"><span class="nav-number">1.38.3.</span> <span class="nav-text">Write</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Or"><span class="nav-number">1.38.3.1.</span> <span class="nav-text">Or:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Placeholders"><span class="nav-number">1.38.4.</span> <span class="nav-text">Placeholders</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Example"><span class="nav-number">1.38.5.</span> <span class="nav-text">Example</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Bytes"><span class="nav-number">1.39.</span> <span class="nav-text">Bytes</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Encode-1"><span class="nav-number">1.39.1.</span> <span class="nav-text">Encode</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Decode-1"><span class="nav-number">1.39.2.</span> <span class="nav-text">Decode</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Read-Bytes-from-File"><span class="nav-number">1.39.3.</span> <span class="nav-text">Read Bytes from File</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Write-Bytes-to-File"><span class="nav-number">1.39.4.</span> <span class="nav-text">Write Bytes to File</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Struct"><span class="nav-number">1.40.</span> <span class="nav-text">Struct</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Example-1"><span class="nav-number">1.40.1.</span> <span class="nav-text">Example</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Format-2"><span class="nav-number">1.40.2.</span> <span class="nav-text">Format</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#For-standard-sizes-start-format-string-with"><span class="nav-number">1.40.2.1.</span> <span class="nav-text">For standard sizes start format string with:</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Integer-types-Use-capital-letter-for-unsigned-type-Standard-sizes-are-in-brackets"><span class="nav-number">1.40.2.2.</span> <span class="nav-text">Integer types. Use capital letter for unsigned type. Standard sizes are in brackets:</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Floating-point-types"><span class="nav-number">1.40.2.3.</span> <span class="nav-text">Floating point types:</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Array"><span class="nav-number">1.41.</span> <span class="nav-text">Array</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Memory-View"><span class="nav-number">1.42.</span> <span class="nav-text">Memory View</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Decode-2"><span class="nav-number">1.42.1.</span> <span class="nav-text">Decode</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Deque"><span class="nav-number">1.43.</span> <span class="nav-text">Deque</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Threading"><span class="nav-number">1.44.</span> <span class="nav-text">Threading</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Thread"><span class="nav-number">1.44.1.</span> <span class="nav-text">Thread</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Lock"><span class="nav-number">1.44.2.</span> <span class="nav-text">Lock</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Or-1"><span class="nav-number">1.44.2.1.</span> <span class="nav-text">Or:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Thread-Pool-Executor"><span class="nav-number">1.44.3.</span> <span class="nav-text">Thread Pool Executor</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Future"><span class="nav-number">1.44.3.1.</span> <span class="nav-text">Future:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Queue"><span class="nav-number">1.44.4.</span> <span class="nav-text">Queue</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Operator"><span class="nav-number">1.45.</span> <span class="nav-text">Operator</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Introspection"><span class="nav-number">1.46.</span> <span class="nav-text">Introspection</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Variables"><span class="nav-number">1.46.1.</span> <span class="nav-text">Variables</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Attributes-1"><span class="nav-number">1.46.2.</span> <span class="nav-text">Attributes</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Parameters-1"><span class="nav-number">1.46.3.</span> <span class="nav-text">Parameters</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Metaprograming"><span class="nav-number">1.47.</span> <span class="nav-text">Metaprograming</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Type-1"><span class="nav-number">1.47.1.</span> <span class="nav-text">Type</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Meta-Class"><span class="nav-number">1.47.2.</span> <span class="nav-text">Meta Class</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Or-2"><span class="nav-number">1.47.2.1.</span> <span class="nav-text">Or:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Metaclass-Attribute"><span class="nav-number">1.47.3.</span> <span class="nav-text">Metaclass Attribute</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Type-Diagram"><span class="nav-number">1.47.4.</span> <span class="nav-text">Type Diagram</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Inheritance-Diagram"><span class="nav-number">1.47.5.</span> <span class="nav-text">Inheritance Diagram</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Eval"><span class="nav-number">1.48.</span> <span class="nav-text">Eval</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Coroutine"><span class="nav-number">1.49.</span> <span class="nav-text">Coroutine</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Helper-Decorator"><span class="nav-number">1.49.1.</span> <span class="nav-text">Helper Decorator</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Pipeline-Example"><span class="nav-number">1.49.2.</span> <span class="nav-text">Pipeline Example</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Libraries"><span class="nav-number">2.</span> <span class="nav-text">Libraries</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Progress-Bar"><span class="nav-number">2.1.</span> <span class="nav-text">Progress Bar</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Plot"><span class="nav-number">2.2.</span> <span class="nav-text">Plot</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Table"><span class="nav-number">2.3.</span> <span class="nav-text">Table</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Prints-a-CSV-file-as-an-ASCII-table"><span class="nav-number">2.3.0.1.</span> <span class="nav-text">Prints a CSV file as an ASCII table:</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Curses"><span class="nav-number">2.4.</span> <span class="nav-text">Curses</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Clears-the-terminal-prints-a-message-and-waits-for-an-ESC-key-press"><span class="nav-number">2.4.0.1.</span> <span class="nav-text">Clears the terminal, prints a message and waits for an ESC key press:</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Logging"><span class="nav-number">2.5.</span> <span class="nav-text">Logging</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Exceptions-2"><span class="nav-number">2.5.1.</span> <span class="nav-text">Exceptions</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Rotation"><span class="nav-number">2.5.2.</span> <span class="nav-text">Rotation</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Retention"><span class="nav-number">2.5.3.</span> <span class="nav-text">Retention</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Scraping"><span class="nav-number">2.6.</span> <span class="nav-text">Scraping</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Scrapes-Python’s-URL-version-number-and-logo-from-Wikipedia-page"><span class="nav-number">2.6.0.1.</span> <span class="nav-text">Scrapes Python’s URL, version number and logo from Wikipedia page:</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Web"><span class="nav-number">2.7.</span> <span class="nav-text">Web</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Run"><span class="nav-number">2.7.1.</span> <span class="nav-text">Run</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Static-Request"><span class="nav-number">2.7.2.</span> <span class="nav-text">Static Request</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Dynamic-Request"><span class="nav-number">2.7.3.</span> <span class="nav-text">Dynamic Request</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#REST-Request"><span class="nav-number">2.7.4.</span> <span class="nav-text">REST Request</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Test"><span class="nav-number">2.7.4.1.</span> <span class="nav-text">Test:</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Profiling"><span class="nav-number">2.8.</span> <span class="nav-text">Profiling</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Stopwatch"><span class="nav-number">2.8.1.</span> <span class="nav-text">Stopwatch</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#High-performance"><span class="nav-number">2.8.1.1.</span> <span class="nav-text">High performance:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Timing-a-Snippet"><span class="nav-number">2.8.2.</span> <span class="nav-text">Timing a Snippet</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Profiling-by-Line"><span class="nav-number">2.8.3.</span> <span class="nav-text">Profiling by Line</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Call-Graph"><span class="nav-number">2.8.4.</span> <span class="nav-text">Call Graph</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Generates-a-PNG-image-of-a-call-graph-with-highlighted-bottlenecks"><span class="nav-number">2.8.4.1.</span> <span class="nav-text">Generates a PNG image of a call graph with highlighted bottlenecks:</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#NumPy"><span class="nav-number">2.9.</span> <span class="nav-text">NumPy</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Indexing"><span class="nav-number">2.9.1.</span> <span class="nav-text">Indexing</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Broadcasting"><span class="nav-number">2.9.2.</span> <span class="nav-text">Broadcasting</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-If-array-shapes-differ-in-length-left-pad-the-shorter-shape-with-ones"><span class="nav-number">2.9.2.1.</span> <span class="nav-text">1. If array shapes differ in length, left-pad the shorter shape with ones:</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-If-any-dimensions-differ-in-size-expand-the-ones-that-have-size-1-by-duplicating-their-elements"><span class="nav-number">2.9.2.2.</span> <span class="nav-text">2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-If-neither-non-matching-dimension-has-size-1-rise-an-error"><span class="nav-number">2.9.2.3.</span> <span class="nav-text">3. If neither non-matching dimension has size 1, rise an error.</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Example-2"><span class="nav-number">2.9.3.</span> <span class="nav-text">Example</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#For-each-point-returns-index-of-its-nearest-point-0-1-0-6-0-8-gt-1-2-1"><span class="nav-number">2.9.3.1.</span> <span class="nav-text">For each point returns index of its nearest point ([0.1, 0.6, 0.8] =&gt; [1, 2, 1]):</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Image"><span class="nav-number">2.10.</span> <span class="nav-text">Image</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Modes-1"><span class="nav-number">2.10.1.</span> <span class="nav-text">Modes</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Examples"><span class="nav-number">2.10.2.</span> <span class="nav-text">Examples</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Creates-a-PNG-image-of-a-rainbow-gradient"><span class="nav-number">2.10.2.1.</span> <span class="nav-text">Creates a PNG image of a rainbow gradient:</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Adds-noise-to-a-PNG-image"><span class="nav-number">2.10.2.2.</span> <span class="nav-text">Adds noise to a PNG image:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Drawing"><span class="nav-number">2.10.3.</span> <span class="nav-text">Drawing</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Animation"><span class="nav-number">2.11.</span> <span class="nav-text">Animation</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Creates-a-GIF-of-a-bouncing-ball"><span class="nav-number">2.11.0.1.</span> <span class="nav-text">Creates a GIF of a bouncing ball:</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Audio"><span class="nav-number">2.12.</span> <span class="nav-text">Audio</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Sample-Values"><span class="nav-number">2.12.1.</span> <span class="nav-text">Sample Values</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Read-Float-Samples-from-WAV-File"><span class="nav-number">2.12.2.</span> <span class="nav-text">Read Float Samples from WAV File</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Write-Float-Samples-to-WAV-File"><span class="nav-number">2.12.3.</span> <span class="nav-text">Write Float Samples to WAV File</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Examples-1"><span class="nav-number">2.12.4.</span> <span class="nav-text">Examples</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Saves-a-sine-wave-to-a-mono-WAV-file"><span class="nav-number">2.12.4.1.</span> <span class="nav-text">Saves a sine wave to a mono WAV file:</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Adds-noise-to-a-mono-WAV-file"><span class="nav-number">2.12.4.2.</span> <span class="nav-text">Adds noise to a mono WAV file:</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Plays-a-WAV-file"><span class="nav-number">2.12.4.3.</span> <span class="nav-text">Plays a WAV file:</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Text-to-Speech"><span class="nav-number">2.12.5.</span> <span class="nav-text">Text to Speech</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Synthesizer"><span class="nav-number">2.13.</span> <span class="nav-text">Synthesizer</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Plays-Popcorn-by-Gershon-Kingsley"><span class="nav-number">2.13.0.1.</span> <span class="nav-text">Plays Popcorn by Gershon Kingsley:</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Basic-Script-Template"><span class="nav-number">2.14.</span> <span class="nav-text">Basic Script Template</span></a></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">srat1999</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">70.1k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







  <div>
    <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1278555274'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s4.cnzz.com/z_stat.php%3Fid%3D1278555274%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));</script>
    <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1278555274'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s4.cnzz.com/z_stat.php%3Fid%3D1278555274%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
  </div>
 



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
